Search code examples
csegmentation-faultfgets

How do you locate and fix a segfault?


I have been looking around the internet and SO, and am trying to find how to detect and fix segfaults. I tend to get this error a lot, and all I could find on google and SO was it is a memory issue(This answer helped a lot: https://stackoverflow.com/a/3200536/3334282). I want to know what the poor programming is that causes it so that I can avoid it.

My most recent example was trying to learn how to use fgets().

FILE *text;
char array[100];

fopen("text.txt", "r");
fgets(array, 100, text);

printf("%s\n", array);

fclose(text);

This returns 8181 segmentation fault (core dumped).


Solution

  • In this case it's very obvious: Where do you initialize text?

    Uninitialized local variables have an indeterminate value, and using uninitialized local variables leads to undefined behavior which can lead to crashes.


    For the more generic question as phrased in the question title, that's harder because quite a few things can cause segmentation faults. Using uninitialized pointers may cause it, using NULL pointers most definitely will cause a crash. Writing outside of bounds for allocated memory (like writing out of bounds for arrays), can overwrite other data making other pointers change their values unexpectedly and that can lead to a crash as well.

    In short, using pointers can lead to segmentation faults if used improperly.

    However, many cases of undefined behavior, like the one in your code, can be avoided by enabling more warnings (like e.g. -Wall flag to GCC) and fixing those warnings. While warnings are technically not errors, they are often an indicator of you doing something suspicious. Again with your code as example, by adding -Wall to your GCC command line, you would have gotten a warning about using the uninitialized variable text.