使用 realloc() 初始化内存

Initializing the memory using realloc()

关于realloc()的问题。

如果我想扩大我之前分配的内存 realloc()

附加内存会不会像calloc()一样初始化为0?

第二个问题是:

    int * p =(int*)malloc(10*sizeof(int));
    int* s = (int*)realloc(p,20);
    p=s;

s 分配给 p 是调整指针 p 大小的好方法吗?

我们可以 realloc() 使用 calloc() 分配的内存吗?

Will the additional memory be initialized to 0?

没有

can we realloc() the memory allocated with calloc()?

是的。

Is assigning s to p a good way to resize the pointer p

视情况而定。

正在做

int * p = malloc(...);
int * s = realloc(p, ...);
p = s;

相同
int * p = malloc(...);
p = realloc(p, ...);
int * s = p;

在这两种情况下,如果 realloc() 失败(并返回 NULL),原始内存的地址将丢失。

但是在做

int * p = malloc(...);

{
  int * s = realloc(p, ...); /* Could use a void* here as well. */
  if (NULL == s)
  {
     /* handle error */
  }
  else
  {
    p = s;
  }
}

realloc() 的故障具有鲁棒性。即使在失败的情况下,原始内存仍然可以通过 p.

访问

请注意,如果realloc() 成功,传入的指针值不一定再寻址任何有效内存。 不要读取它,也不要读取指针值本身,因为在这两种情况下都这样做可能会引发未定义的行为。