如果没有连续的内存空间,realloc会怎么做?

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)


Ric*_*dle 6

realloc只有当它能够返回连续的(你的话中的"顺序")内存块时才会成功.如果不存在这样的块,它将返回NULL.

  • @Mark - 原始内存保持不变.这个上下文中常见的错误是'x = realloc(x)' - 你必须做'newX = realloc(x)'以避免在出错时泄漏原始x. (4认同)