ccode-analysis

finding errors in a given c code


I am interested to know on what things I need to concentrate on debugging c code without a debugger. What are the things to look for?

Generally I look for the following:

  1. Check whether correct value and type is being passed to a function.
  2. Look for unallocated and uninitialized variables
  3. Check for function syntax and function is used in right way.
  4. Check for return values
  5. Check for locks are used in the right way.
  6. Check for string termination
  7. Returning a varible in stack memory from a function
  8. Off by one errors
  9. Normal syntax errors
  10. Function declaration errors

Any structured approach is very much appreciated.


Solution

  • Most of these errors will be picked up by passing the appropriate warning flags to the compiler.

    However from the original list, points 1, 5, 6, 7, 8 are very much worth checking as a human, some compiler/flag combinations however will pick up on unhandled values, pointers to automatic memory, and off-by-one errors in array indexing etc.

    You may want to take a look at such things as mudflap, valgrind, efence and others to catch runtime cases you're unaware of. You might also try splint, to augment your static analysis.

    For the unautomated side of things, try statically following the flow of your program for particular cases, especially corner cases, and verify to yourself that it appears to do the right thing. Try writing unit tests/test scripts. Be sure to use some automated checking as discussed above.

    If your emphasis is on testing without any test execution, splint might very well be the best place to start. The technique you want to research is called static code analysis.