realloc
用于动态重新分配内存。
假设我使用 malloc
函数分配了 7 个字节,现在我想将其扩展为 30 个字节。
如果内存中没有连续的 30 个字节的空间,后台会发生什么情况?
会出现错误还是内存会被分配成多个部分?
realloc
用于动态重新分配内存。
假设我使用 malloc
函数分配了 7 个字节,现在我想将其扩展为 30 个字节。
如果内存中没有连续的 30 个字节的空间,后台会发生什么情况?
会出现错误还是内存会被分配成多个部分?
realloc
的实现大致如下:
NULL
来报告失败。因此,您可以通过测试NULL
来检测失败,但要注意不要过早地覆盖旧指针:
int* p = malloc(x);
/* ... */
p = realloc(p, y); /* WRONG: Old pointer lost if realloc fails: memory leak! */
/* Correct way: */
{
int* temp = realloc(p, y);
if (NULL == temp)
{
/* Handle error; p is still valid */
}
else
{
/* p now possibly points to deallocated memory. Overwrite it with the pointer
to the new block, to start using that */
p = temp;
}
}
realloc
只有在能够返回连续的内存块时才会成功。如果不存在这样的内存块,它将返回NULL
。
if (!x) exit(1);
,那么这就不是一个 bug 了 :-) - R.. GitHub STOP HELPING ICE来自man page:
realloc()返回指向新分配的内存的指针,该内存适合任何类型的变量并且可能与ptr不同,如果请求失败则为NULL。
换句话说,要检测失败,只需检查结果是否为NULL。
编辑:如评论中所述,如果调用失败,则原始内存不会被释放。
一般而言,这取决于实现方式。在x86(-64) Linux上,我相信标准的doug lea malloc算法将始终分配至少一个标准的x86页面(4096字节),因此对于您上述描述的情况,它只会重置边界以适应额外的字节。当涉及到将7字节的缓冲区重新分配为PAGE_SIZE+1时,我相信它将尝试分配下一个连续的页面(如果有的话)。
如果您正在Linux上开发,请阅读以下内容:
By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available. This is a really bad bug. In case it turns out that the system is out of memory, one or more processes will be killed by the infamous OOM killer. In case Linux is employed under circumstances where it would be less desirable to suddenly lose some randomly picked processes, and moreover the kernel version is sufficiently recent, one can switch off this overcommitting behavior using a command like:
# echo 2 > /proc/sys/vm/overcommit_memory
See also the kernel Documentation directory, files vm/overcommit-accounting and sysctl/vm.txt.
FreeBSD和Mac OS X都有reallocf()函数,当请求的内存无法分配时,该函数将释放传递的指针(请参阅man realloc)。
realloc
函数适用于所有实现吗? - Spikatrixrealloc
的可观察行为。 - Bart van Ingen Schenau