使用realloc缩小内存分配

Cha*_*les 0 c malloc standards memory-management c99

我想用来realloc从大块内存的末尾释放内存.我知道标准不要求realloc成功,即使请求的内存低于原始malloc/ calloc调用.我可以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;
Run Code Online (Sandbox Code Playgroud)

这不是一个小优化; 我要保存的部分可能只有原始长度的5%,可能是几千兆字节.


注意:使用realloc缩小已分配的内存,如果新块大小小于初始值,是否应强制执行realloc检查?是相似但不解决我的特定问题.

fuz*_*fuz 7

是的你可以.如果realloc()不成功,原始内存区域保持不变.我通常使用这样的代码:

/* shrink buf to size if possible */
void *newbuf = realloc(buf, size);
if (newbuf != NULL)
    buf = newbuf;
Run Code Online (Sandbox Code Playgroud)

确保size不是零.realloc()使用零长度数组的行为取决于实现,并且可能是麻烦的来源.有关详情,请参阅此问题.