使用 realloc 缩小内存分配
Using realloc to shrink memory allocation
我想使用realloc
从内存块的末尾释放内存。我知道标准不要求 realloc
成功,即使请求的内存低于原始 malloc
/calloc
调用。我可以只 realloc
,然后如果它失败 returns 原来的吗?
// 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 and 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。
我想使用realloc
从内存块的末尾释放内存。我知道标准不要求 realloc
成功,即使请求的内存低于原始 malloc
/calloc
调用。我可以只 realloc
,然后如果它失败 returns 原来的吗?
// 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 and 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。