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;
CodePudding user response:
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.
CodePudding user response:
Is it mandatory to check if realloc worked?
Yes, or at least, as mandatory as is to check any other success/failure return.
realloc
can certainly fail, just as malloc
can. In fact, realloc
can fail even if you're trying to make a block smaller.
Now, if you're working on the assumption that malloc
on a virtual memory system can never fail, and if you're not checking the return value from malloc
, either, then no, with the same justification, you could skip checking realloc
's return value also. (It'd be silly to check realloc
's return value but not malloc
's.)
In practice, the question of whether to check for memory allocation failure (malloc
and/or realloc
) on a modern, virtual-memory system is the subject of some debate. There are plenty of programmers who believe that checking the return values is a waste of time, since "malloc
never fails". Me, I always check (except in the very most rushed, throwaway code), because even after all these years, the number of times I've said "I'm getting so tired of typing if( … != NULL)
all the time!" is still zero, while the number of times that a checked and caught NULL return has alerted me promptly to a bug in my code, and saved me hours of pointless debugging, is countless.
So in summary, and at the risk of repeating myself, I'd say that, yes, it's mandatory. See also Always check malloc'ed memory?
CodePudding user response:
It is a return value from a library function. The language has no knowledge of the semantics of any function and it is not syntactically mandatory to check or use any return value. That is to say it will compile.
However it may be a semantic error not to check, and an unchecked failure may cause unintended runtime behaviour - i.e. a bug. The language does not prevent you from writing bugs.
It may be "mandatory" in a "local" sense, in cases where development is subjected a coding standard that makes it so. Any reasonable coding standard would likely impose such a requirement, and that might be enforced by static analysis tools or peer review used by the development team. But not universally mandatory. You are free to write bad code if such standards are not applied to your project.