简体   繁体   中英

Using realloc to shrink memory allocation

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.

Yes, you can. If realloc() is not successful, the original memory region is left untouched. I usually use code like this:

/* shrink buf to size if possible */
void *newbuf = realloc(buf, size);
if (newbuf != NULL)
    buf = newbuf;

Make sure that size is not zero. The behaviour of realloc() with a zero-length array depends on the implementation and can be a source of trouble. See this question for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM