Do not use realloc(ptr, 0) as free(ptr)

suggest change

Use free(ptr) when the intent is to release an allocation. In C23, calling realloc with a size of zero has undefined behavior.

Earlier C standards permitted implementation-defined results for zero-size reallocation, and implementations did not all agree about whether the original allocation was released. Code could therefore confuse a successful deallocation with an allocation failure or leak the original allocation.

For a nonzero size, assign the result of realloc to a temporary pointer. If the call fails, the original allocation remains valid:

void *resized = realloc(ptr, new_size);
if (resized == NULL) {
    /* ptr is still valid; handle the allocation failure. */
} else {
    ptr = resized;
}

Handle a zero requested size separately:

if (new_size == 0) {
    free(ptr);
    ptr = NULL;
} else {
    void *resized = realloc(ptr, new_size);
    if (resized != NULL) {
        ptr = resized;
    }
    /* On failure ptr is unchanged. This fragment does not report the error. */
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents