简体   繁体   English

使用realloc()初始化内存

[英]Initializing the memory using realloc()

The question about realloc() . 关于realloc()的问题。

If I want to size up the memory I allocated before with realloc() . 如果我想用realloc()分配之前分配的内存,请执行以下操作。

Will the additional memory be initialized to 0 just like calloc() or not? 是否像calloc()一样将额外的内存初始化为0?

The second question is: 第二个问题是:

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

Is assigning s to p a good way to resize the pointer p ? s分配给p是调整指针p大小的好方法吗?

And can we realloc() the memory allocated with calloc() ? 我们可以realloc()calloc()分配的内存吗?

Will the additional memory be initialized to 0? 将额外的内存初始化为0吗?

No. 没有。

can we realloc() the memory allocated with calloc() ? 我们可以realloc()calloc()分配的内存吗?

Yes. 是。

Is assigning s to p a good way to resize the pointer p s分配给p是调整指针p大小的好方法

Depends. 要看。

Just doing 只是做

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

is the same as 是相同的

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

In both cases, if realloc() fails (and with this returned NULL ) the address of the original memory is lost. 在这两种情况下,如果realloc()失败(并返回此NULL ),则原始内存的地址将丢失。

But doing 但是做

int * p = malloc(...);

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

is robust against failures of realloc() . 对于realloc()失败具有鲁棒性。 Even in case of failure the original memory is still accessible via p . 即使出现故障,仍然可以通过p访问原始内存。

Please note that if realloc() succeeded the value of the pointer passed in not necessarily addresses any valid memory any more. 请注意,如果realloc() 成功 ,则传入的指针的值不必再寻址任何有效内存。 Do not read it, nor read the pointer value itself, as doing this in both cases could invoke undefined behaviour. 不要读它,也不会读指针值本身,在这两种情况下,这样做可能会发生未定义行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM