Always check for NULL (in C)

This tip submitted by Webmaster on 2004-12-29 00:00:00. It has been viewed 88769 times.
Rating of 5.6 with 336 votes



Malloc can fail. When you call malloc, or when you get a pointer back from a function that calls malloc, you should check to ensure that the pointer you got back wasn't NULL.

char *getMemory()
{
    char *newMem = malloc(20);
    if(newMem == NULL)
    { 
         return NULL;
    }
    /* do some things to set newMem */
    return newMem;
}

void useMemory()
{
    char *newMem = getMemory();
    newMem[0] = 'a'; /* bad */
}


It's important to check for NULL in getMemory if you're going to use that memory later, but it's also important to make sure that getMemory doesn't return NULL.

(The same does not go for calling new in C++ -- check this FAQ entry for more details.)

Note that you do not need to check for NULL before calling free. For instance, the following is perfectly valid.

int *x = NULL;
free(x):


If you're interested in a difference between C and C++, check out this tip on memory allocation in C++.



More tips

Help your fellow programmers! Add a tip!