我想使用 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;
这不是一个小的优化;我要保存的部分可能只有原始长度的 5%,可能有几千兆字节。
备注:Using realloc to shrink the allocated memory和 Should I enforce realloc check if the new block size is smaller than the initial?相似但不解决我的特定问题。
最佳答案
是的,你可以。如果 realloc()
不成功,则原始内存区域保持不变。我通常使用这样的代码:
/* shrink buf to size if possible */
void *newbuf = realloc(buf, size);
if (newbuf != NULL)
buf = newbuf;
确保 size
不为零。具有零长度数组的 realloc()
的行为取决于实现,并且可能是麻烦的根源。参见 this question了解详情。
关于c - 使用 realloc 缩小内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36066263/