malloc(0) zero-size allocation returns NULL or non-null by implementation
0 reputation · 22 Jun 2025, 21:44 UTC
0 reputation · 22 Jun 2025, 21:44 UTC
I need to allocate a zero-sized block with malloc(0) in portable C code and handle the result correctly across different C library implementations.
The C standard leaves malloc(0) implementation-defined: it may return NULL or a pointer to a zero-size object that must not be dereferenced. There is no standard feature-test macro to select the behavior, and NULL is not a dependable out-of-memory indicator for zero-size requests. Reading or writing through the returned pointer is undefined behavior even when it is non-null.
What is the correct portable pattern for checking malloc(0) before calling free()? Should code treat both NULL and non-null returns as valid, and are there exceptions where one outcome can be safely assumed?
The C standard (C99-C17) specifies that malloc(0) yields either NULL or a unique non-NULL pointer; the result is implementation-defined. The only portable guarantee is that the pointer may be passed to free and that free(NULL) is a no-op.
void *p = malloc(0);free(p); - this is safe whether p is NULL or non-NULL.malloc(0) on several libc versions and prints the returned pointer.free to confirm that both NULL and non-NULL are accepted.free(NULL) does not segfault, verifying the no-op behavior.#include
#include
int main(void) {
void *p = malloc(0);
printf("malloc(0) returned %p\n", (void *)p);
free(p); // safe for NULL and non-NULL
return 0;
}
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.