Will the additional memory be initialized to 0?
No.
can we realloc()
the memory allocated with calloc()
?
Yes.
Is assigning s
to p
a good way to resize the pointer 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.
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()
. Even in case of failure the original memory is still accessible via p
.
Please note that if realloc()
succeeded the value of the pointer passed in not necessarily addresses any valid memory any more. Do not read it, nor read the pointer value itself, as doing this in both cases could invoke undefined behaviour.