关于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 withcalloc()
?
是的。
Is assigning
s
top
a good way to resize the pointerp
视情况而定。
只是做
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()
成功 传入的指针值不一定再寻址任何有效内存。不要读取它,也不要读取指针值本身,因为在这两种情况下这样做都可能引发未定义的行为。
关于c - 使用 realloc() 初始化内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54379535/