[英]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 withcalloc()
?我们可以
realloc()
用calloc()
分配的内存吗?
Yes. 是。
Is assigning
s
top
a good way to resize the pointerp
将
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.