Search code examples
cdynamic-memory-allocationrealloc

Is it mandatory to check if realloc worked?


In C is it mandatory to check if the realloc function made it?

void *tmp = realloc(data, new_size);
if (tmp == NULL) return 1;
data = tmp;

Solution

  • In C is it mandatory to check if the realloc function made it?

    The quick answer is: NO! checking for failure is not mandatory. If realloc fails, it returns a null pointer, storing it into the original pointer overwrites the previous value, potentially making the block unreachable for later freeing. Dereferencing this null pointer has undefined behavior, a crash on architectures with protected virtual memory. In practice, on these systems with virtual memory, unless you pass an insanely large number for the new size, the call will not fail so you wont get hit by this sloppy code:

    data = realloc(data, new_size); // assume realloc succeeds
    

    If you care to be friendly to the next guy trying to debug the program in more stressed environments, you could add:

    data = realloc(data, new_size); // assume realloc succeeds
    assert(data);
    

    The long answer is: YES you should check for realloc failure in a reliable production program and handle the failure gracefully.

    Obviously realloc can fail if you the requested amount of memory is too large for the heap to honor, but it can also fail for internal reasons for requests for smaller amounts, even amounts smaller than the size of the allocated block passed as an argument, even in the absence of heap corruption caused by undefined behavior. There is just no reason to assume that realloc() will always succeed.

    If you know the current size allocated for the object you mean to realloc, you can ignore a realloc failure to shrink the object.

    For other requests, you should handle handle the error gracefully. If the error causes the function to abort its operation, any memory allocated for the current task should be free'd to avoid memory leaks if the calling program continues. This is a recommendation to avoid memory or resource leaks and allow the program to run reliably for a long time, but depending on your local constraints, you may get away with slack.


    To summarize: depending on local constraints (from quick and dirty throw away code to reliable sturdy production code running indefinitely in a life support system), you might not care about the potential improbable failures or it could be mandatory for you to detect, handle and document any unexpected situations.

    Detecting and reporting less improbable errors such as fopen() failure to open files, fgets() failure at end of file or scanf() conversion errors from invalid user input is recommended to avoid wasting hours trying to make sense of unexpected behavior, or worse relying on corrupted data that did not produce obviously incorrect results.