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
.