Jon.e, there are some reasons for SEGFAULT.
Even when there is no bug at all, but rather there are a lack of memory.
Some guys tell you, to pay attention to compiler message and warning, yes, but that's just a part of story.
Related to SEGFAULT there are the following most notable kinds of SEGFAULTS, that I can tell you by my own experience:
1. You are trying to access to indices which do not exist.
Array has the size, exactly same size which you have specified while declaring an array.
Review this code:
/* "Array out of bounds" error
valid indices for array foo
are 0, 1, ... 999 */
int foo[1000];
for (int i = 0; i <= 1000 ; i++)
foo[i] = i;
Here we have one illegal access to an index which does not exist.
2. You are trying to access to the value which does not exist.
In this case memory exists but the value...
/* Illegal memory access if value of n is
not in the range 0, 1, ... 999 */
int n;
int foo[1000];
for (int i = 0; i < n ; i++)
foo[i] = i;
This is also one of the most common pitfalls.
This pitfall is so fundamental, even experienced developers sometime make such mistake. The problem is in uninitialized memory for variable n.
Initialization is process of putting value of the variable its first value, If you want, we can say that it's process of losing virginity of the variable.
There are very chaotic rule of when variable is initialized and when - not. To complex for remembering. Just always initialize variables.
3. You are trying to access to the memory via pointers.
And that pointer does not point anywhere. You are trying to read something from NOWHERE? It does not make sense, does it?
/* Illegal memory access because no memory
is allocated for foo2 */
float *foo, *foo2;
foo = (float*)malloc(1000);
foo2[0] = 1.0;
What happens, if you forget to initialize variable( 2-nd ) or pointer (3-rd case). The answer is broad: from nothing to catastrophe.
Why so? Because memory is the something which has been used by a lot of applications, and it's shared between hundreds of thousands applications running on a computer. So when you create a variable it creates the segment in the memory for that variables, but does not clean that memory (to be precise, in some cases it has been nulled, in others - not) Just assume that is never cleared. So in such situations, no matter the problem caused by variable or by pointer (which is actually is a variable too, but that's another story), we say that, variable stores 'garbage'.
Note, it's not obvious, to find those kind of SEGFAULTS, sometimes it's almost impossible, so you must be ready for such situations, and should use debugger for example gdb, to eliminate the bug.
Also avoid such dummy errors, like. The practice with my students show that it's very very common error.
int n = 100;
int foo[n];
use instead
int foo[100]
or
const int n = 100;
int foo[n];
or
enum N { N = 100 };
int is[N];
Additional references:
Can a const variable be used to declare the size of an array in C?
https://kb.iu.edu/d/aqsj