Sam*_*ain 11 c realloc dynamic-memory-allocation
realloc 用于动态重新分配内存.
假设我已经使用该malloc函数分配了7个字节,现在我想将其扩展到30个字节.
如果内存中没有30个字节的连续(连续单行)空间,后台会发生什么?
是否有任何错误或内存将被分配?
Bar*_*nau 11
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;
}
}
Run Code Online (Sandbox Code Playgroud)
realloc只有当它能够返回连续的(你的话中的"顺序")内存块时才会成功.如果不存在这样的块,它将返回NULL.