Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Exception has occured. Segmentation Fault

I am getting this segmentation error and I can seem to find where it is occuring. I am trying to create a list of float values through an array of floats. It is one of my assignment from college class.
my code

I have tried to comment out the float array all together to see if that is where the error is occuring but it seems the error always happens after scanf and it asks for a user size of the array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The code segfaults because scanf() expects a pointer to store the data that was read.

In your case scanf("%d", size); with size initialized to 0 (see size = 0) means scanf should store the data at address 0 which is an invalid pointer to write and read from (NULL pointer).

However, it doesn’t really matter that you’re trying to write to a NULL pointer, any other fixed pointer would most likely cause a segfault too (i.e. if size were 2 or 242353252 it would still segfault). Segfault simply means your program accessed an invalid memory location ; and there are A LOT of invalid memory locations that could be accessed by your program.

That’s why your program segfaults.

To get the address of a variable use the & operator:

scanf("%d", &size);

Now scanf receives the address of whatever address size is stored at.


scanf("%d", &numList[i]);

Is also wrong, but for a different reason: %d expects an int variable, but you’re passing the address of a float variable.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading