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会做什么? - 代码日志