Reallocating Memory
suggest changeYou may need to expand or shrink your pointer storage space after you have allocated memory to it. On success, realloc(ptr, size) releases the old object and returns a pointer to an object of the new size. ptr must be a null pointer or a pointer previously returned by malloc, calloc, or realloc and not yet freed. As much of the old contents as fits is preserved. If the new size is larger, the additional bytes are uninitialized. If the new size is smaller, the truncated part is lost. If ptr is null, the call allocates a new block. If the call fails, the old object is left in place and the return value is a null pointer.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *p = malloc(10 * sizeof *p);
if (NULL == p)
{
perror("malloc() failed");
return EXIT_FAILURE;
}
p[0] = 42;
p[9] = 15;
/* Reallocate array to a larger size, storing the result into a
* temporary pointer in case realloc() fails. */
{
int *temporary = realloc(p, 1000000 * sizeof *temporary);
/* realloc() failed, the original allocation was not free'd yet. */
if (NULL == temporary)
{
perror("realloc() failed");
free(p); /* Clean up. */
return EXIT_FAILURE;
}
p = temporary;
}
/* From here on, array can be used with the new size it was
* realloc'ed to, until it is free'd. */
/* The values of p[0] to p[9] are preserved, so this will print:
42 15
*/
printf("%d %d\n", p[0], p[9]);
free(p);
return EXIT_SUCCESS;
}
The reallocated object may or may not have the same address as the old p. Capture the return value, which is the new address when the call succeeds.
Make sure you assign the return value of realloc to a temporary instead of the original p. realloc will return null in case of any failure, which would overwrite the pointer. This would lose your data and create a memory leak.