Monday, February 23, 2009

Always check for NULL (in C)

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.

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):

Author : Webmaster

0 nhận xét:

Post a Comment