Check malloc's return value and handle allocation failure
malloc(3) returns NULL and sets ENOMEM when it cannot allocate. Test it before use, and know that Linux overcommit often kills the process instead of failing.
The rule is old and still ignored: malloc can return NULL, and writing through that pointer is undefined behaviour. The cleanest way to see the failure path is to make allocation fail on purpose. A cap on address space with setrlimit(RLIMIT_AS) does it without exhausting the machine.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
int main(void) {
struct rlimit lim = { .rlim_cur = 256UL << 20, .rlim_max = 256UL << 20 };
if (setrlimit(RLIMIT_AS, &lim) < 0) { perror("setrlimit"); return 1; }
char *big = malloc(1UL << 30); /* 1 GiB */
if (big == NULL) {
fprintf(stderr, "malloc failed: %s\n", strerror(errno));
return 1;
}
big[0] = 1;
free(big);
return 0;
}malloc failed: Cannot allocate memoryOn Linux, with the default overcommit heuristic, a large request usually succeeds and the failure shows up later: the OOM killer ends a process when pages are touched and RAM runs out. Only a hard limit like RLIMIT_AS, a container memory cap on address space, or vm.overcommit_memory=2 makes malloc itself return NULL. That is why the check is still needed. It guards embedded targets, servers with limits set, and 32-bit builds, and it costs one branch.
malloc(3) sets errno to ENOMEM. Decide what failure means before you write the call: return an error to the caller, free what was built so far, or abort in a main program with a clear message. malloc(0) may return NULL or a unique pointer, so do not use NULL alone as the failure signal when the size can be zero.