简体   繁体   English

使用realloc缩小内存分配

[英]Using realloc to shrink memory allocation

I want to use realloc to free memory from the end of a chunk of memory. 我想使用realloc从一块内存的末尾释放内存。 I understand that the standard does not require that realloc succeed, even if the memory requested is lower than the original malloc / calloc call. 我了解该标准不要求重新realloc成功,即使请求的内存低于原始malloc / calloc调用也是如此。 Can I just realloc , and then if it fails returns the original? 我可以重新realloc ,如果失败,则返回原始值吗?

// 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. 我要保存的部分可能只有原始长度的5%,可能是几GB。


Note: Using realloc to shrink the allocated memory and Should I enforce realloc check if the new block size is smaller than the initial? 注意: 使用realloc缩小分配的内存是否应该执行realloc检查新块大小是否小于初始块大小? are similar but do not address my particular question. 相似,但没有解决我的特定问题。

Yes, you can. 是的你可以。 If realloc() is not successful, the original memory region is left untouched. 如果realloc()不成功,则原始内存区域保持不变。 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. 确保size不为零。 The behaviour of realloc() with a zero-length array depends on the implementation and can be a source of trouble. 带有零长度数组的realloc()的行为取决于实现,并且可能会引起麻烦。 See this question for details. 有关详细信息,请参见此问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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