I want to use realloc
to free memory from the end of a chunk of memory. I understand that the standard does not require that realloc
succeed, even if the memory requested is lower than the original malloc
/calloc
call. Can I just realloc
, and then if it fails returns the original?
// Create and fill thing1
custom_type *thing1 = calloc(big_number, sizeof(custom_type));
// ...
// Now only the beginning of thing1 is needed
assert(big_number > small_number);
custom_type *thing2 = realloc(thing1, sizeof(custom_type)*small_number);
// If all is right and just in the world, thing1 was resized in-place
// If not, but it could be copied elsewhere, this still works
if (thing2) return thing2;
// If thing2 could not be resized in-place and also we're out of memory,
// return the original object with extra garbage at the end.
return thing1;
This is not a minor optimization; the part I want to save might be as little as 5% of the length of the original, which could be several gigabytes.
Note: Using realloc to shrink the allocated memory and Should I enforce realloc check if the new block size is smaller than the initial? are similar but do not address my particular question.