C Error Checking and Handling – How to Improve

assertionsctesting

Lately I have been struggling to understand what the right amount of checking is and what the proper methods are.

I have a few questions regarding this:

What is the proper way to check for errors (bad input, bad states, etc)? Is it better to explicitly check for errors, or use functions like asserts which can be optimized out of your final code? I feel like explicitly checking clutters a program with a lot of extra code which shouldn't be executed in most situations anyway– and not to mention most errors end up with an abort/exit failure. Why clutter a function with explicit checks just to abort? I have looked for asserts versus explicit checking of errors and found little to truly explain when to do either.

Most say 'use asserts to check for logic errors and use explicit checks to check for other failures.' This doesn't seem to get us very far though. Would we say this is feasible:

Malloc returning null, check explictly
API user inserting odd input for functions, use asserts

Would this make me any better at error checking? What else can I do? I really want to improve and write better, 'professional' code.

Best Answer

The easiest way for me to tell the difference is to determine whether the error condition is introduced at compile time or run time. If the problem is a programmer using the function wrong somehow, make it an assert to draw attention to the problem, but once the fix is compiled into the calling code, you don't need to worry about checking for it any more. Problems like running out of memory or bad end user input can't be solved at compile time, so you leave the checks in.

Related Topic