Debugging in C Guidelines
Finding Bugs
To find bugs in your code, follow the steps below.
- If you are getting a segmentation fault, check your code
using valgrind or
gdb.
- Make sure you are generating the expected results by using
diff.
-
If your code generates the expected results in grace, but not
in the submit server try Valgrind.
valgrind can help identify the use of uninitialized variables
and problems with dynamic memory allocation. It is extremely
helpful.
-
Compile your code with gcc flags.
-
Run splint on your code. For example, splint my_prog.c.
-
If none of the above steps identify the problem,
try the following:
- Simplify the input/case that is generating the problem.
- Once you have simplified the input/case, use the debugger
(gdb) to step through your code. Information on
gdb basics can be found at gdb.
Frequently Seen Mistakes
-
You get the correct results in grace, but not in the submit
server - This may happen because:
- You have uninitialized variables. Grace seems to set
uninitialized variables to 0.
- Your strings are missing a null character ('\0').
- You are not declaring an array that is large enough.
- You are passing to a function a pointer to a character
rather than a pointer to an array of characters.
-
Your code might be generating a core dump in the submit server
if, for a test, the submit server displays a message along the lines
"expected ... but output ended".