Search code examples
cmallocassert

Handling error checking with assert


I've looked all over and it seems that there are a lot of mixed views on assert. For example, if I'm malloc'ing a pointer and want to make sure it's been allocated correctly I'd write:

p = malloc(sizeof(int));
assert(p)

instead of:

p = malloc(sizeof(int));
if (p == NULL)
{
... send error message
}

I know that with assert it will end the program, but for testing purposes — what I want to know is what the absolute safest way of:

  1. testing for things like a malloc being done correctly.
  2. dealing with an error if something isn't malloc'd correctly.

Solution

    1. TESTING FOR THE FAILURE:
      The malloc function is REQUIRED by the C standard to return NULL if the requested amount of memory cannot be given to the program.

      That means that if the return value of malloc is non-NULL, you can be sure that ALL of the memory was properly allocated.

      Checking for a NULL return value is the ONLY way to determine whether or not malloc was successful. The assert function can be used to stop the program if an assertion fails, but in a production release of the program, there must be other error handling.

    2. HANDLING THE FAILURE:
      If the return value is NULL, use the errno variable to determine WHY the failure occurred. The errno variable is also part of the C standard.

      For LINUX, here is the list of values errno can be set to:

      http://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Errors/unix_system_errors.html

    3. IMPORTANT: A malloc failure is a serious error. If this happens in the program execution, don't try to continue to execute additional functionality in the program. Stop (exit from) the program as soon as an error has been logged and reported to the user of the program, as follows:

      You should use the exit function with a non-zero return value to notify the user of the program that the program exited with an error status. The exit function is ALSO part of the C language standard.

      Also, before you exit the program, make sure all other memory that was allocated (prior to the malloc failure) is properly de-allocated.