Failing to Check Return Values from Library Functions

Summary: Always check library function return values.

Almost all library functions return some value—either the result of processing or an error code showing success or failure. You should always check library-function return values, even if you're confident of the result.

This rule is critical when calling a library function such as malloc, which allocates memory at run time:

char *ptr;

ptr = (char *) malloc( BUFSIZE ); /* Error! */

If the call to malloc fails, the pointer ptr is assigned a null (0) value. Using ptr under these circumstances can overwrite unexpected memory addresses or cause a run-time error. The following code checks the return value from malloc:

#define NULL 0

#define BUFSIZE 32768

.

.

.

char *ptr;

if( (ptr = (char *) malloc( BUFSIZE ) ) != NULL )

{

printf( "Copacetic.\n" );

/* Do something useful... */

}

else

printf( "Not enough memory!\n" );