Typical beginner errors that may lead to seg faults are:
Using uninitialised variables (especially for array indexes).
Always initialise variables.
Not checking function return values.
Functions might return special values like a
NULL
pointer or a negative integer to indicate an error. Or the return values indicates that values passed back by arguments are not valid.
Always check for error states and break execution upon errors.
Looping up to and including the length of an array.
The last element of an array is accessed with
length - 1
.
Loop end conditions must be
< length
(not
<=
).
Improper length for arrays using
sizeof
.
Don't use
sizeof
for pointers of dynamically created arrays (it is just the pointer size).
Don't forget to divide by the item size when the items are larger than a byte when determining the length of fixed arrays (use
sizeof(array) / sizeof(array[0])
).
Changing literal array sizes not at all places.
Use a
#define
or the
sizeof
operator at all places where the array length is used.
Improper handling of
NULL
terminated strings.
Forgetting to allocate space for the terminating
NULL
character.
Forgetting to set the terminating
NULL
character.
And probably more. But the above are common and are seen here at CP quite often.
Final tips:
Set the warning level of the compiler to maximum. Some of the above problems like unitialised variables are then detected by the compiler.
Use a static code analyser like
Cppcheck - A tool for static C/C++ code analysis[
^].