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:
malloc
being done correctly.malloc
'd correctly. 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.
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
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.