Dynamic Memory Management

NULL-checking the result of malloc

malloc is a request, and requests can be refused. If the system cannot find enough memory to satisfy your call, malloc does not crash or throw an error — it simply returns NULL, a null pointer meaning no memory was given. NULL-checking is the habit of testing for that NULL before you use the pointer, because using a NULL pointer as if it were real memory is a crash waiting to happen.

Precisely: after every malloc, calloc, or realloc, you should compare the returned pointer against NULL. If it is NULL, the allocation failed and the pointer points to nothing; dereferencing it (reading or writing through it) is undefined behavior, which on most systems means an immediate segmentation fault, but could be worse. The correct pattern is to handle the failure right there — return an error, clean up anything you already allocated, or, for a small program where there is nothing sensible to do, print a message and exit. Only after you have confirmed the pointer is not NULL do you start writing into the block. Skipping this check is one of the most common omissions in beginner C, and it usually goes unnoticed because malloc rarely fails on a modern machine with lots of memory — until the day the request is huge, or the size calculation overflowed, or the machine really is out of memory, and then the program crashes at the unguarded dereference.

Two honest nuances. First, on systems that overcommit memory (many Linux configurations), malloc may succeed and return a non-NULL pointer even when the memory cannot all be backed — the failure then surfaces later as the process being killed, not as a NULL from malloc. So NULL-checking is necessary but not, on every system, a complete guarantee. Second, a failed realloc returns NULL while leaving the original block intact, so you must check it into a temporary variable to avoid leaking the original. The discipline is simple and worth making automatic: never use a freshly allocated pointer without first checking it is not NULL.

int *p = malloc(n * sizeof *p); if (p == NULL) { /* allocation failed */ fprintf(stderr, "out of memory\n"); return -1; /* handle it; do NOT touch p */ } p[0] = 1; /* safe only after the check */

Always test the result against NULL before using it; a NULL dereference is the crash this check prevents.

On overcommitting systems malloc can return non-NULL even when memory is short, so the check is necessary but not a full guarantee everywhere. Still always check — the failure is otherwise an undefined-behavior crash.

Also called
checking for allocation failureguarding malloc配置失敗檢查