c - 使用 realloc 缩小内存分配

标签 c memory-management malloc standards 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;

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


备注:Using realloc to shrink the allocated memoryShould 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/

相关文章:

c - 像这样超出范围会释放关联的内存吗?

C++ malloc/memcpy/free 崩溃

c++ - 被信号中断的系统调用仍需完成

c - 将终端分成多个,并在每个终端上调用程序

c - 如何索引障碍分配

c++ - 我可以使用为某种类型指定的分配器在 C++ 中分配另一种类型的对象吗?

android - 将相机中的图像文件压缩到一定大小

CreateDirectory 因权限被拒绝而失败

C - 删除已打印的换行符

c - 重用 malloc() 分配的内存空间