Q: Various segfault or bus error problems ("Segmentation exception" or "Bus error").
A:
- When dereferencing a pointer value,
or giving it to another component to dereference,
make sure it points somewhere. If
you say "char *s;", then you can't say "strcpy(s, something)" immediately
after.
"s" is uninitialized and you can't assume it points to the zeroth byte of an
array where you can store your data. You have to assign it a value pointing
to such a thing if you want to use it. Better yet, often you can just
declare an array in the first place, rather than a pointer variable.
- Be sure you are not exceeding array bounds, including in string
manipulation. If "s" is a string, then "char t[5000]; strcpy(t, s);" is an
error, because you don't know that s is shorter than 5000 characters.
Check lengths with strlen() to be sure that the string will fit in the target array,
and don't forget to leave room for the terminating zero byte.
- Check error returns from system calls. Even in initial development!
- When you do observe (e.g. with an error return from a system call)
that something shouldn't be done, make sure you
don't do it! I've seen a surprising amount of beginner C code in my life
which checks for error returns from system calls correctly and prints a
nice error message but then comes out of the 'if' and uses the invalid
pointer value anyway, etc.
Apparently this is an easy mistake to make (although it's not clear to me
why).
- You can localize the segfault using gdb.
"gdb" is similar to other debuggers you may have used with other programming
languages (e.g. in CSC 207).
I've written an intro document about using gdb.
- Think methodically; form and reject hypotheses.
Understand everything you write in your program. The fact that your program
does not work is not sufficient motivation to make a particular change.
You have to understand the change you are making and have a good reason to do
it. Debugging involves understanding what was wrong with your program, not
just making the bad behaviour seem to go away.
[full Q&A file]