realloc - grow a malloc'ed region

The function realloc is convenient if you need to grow/shrink a malloc'ed array while keeping the contents intact.

If possible it will grow/shrink the block, without copying.

Or it may allocate a new memory block, copy the contents of the old block, and free the old block.

int *p
p = malloc(100 * sizeof (int));      /* array length is 100 */
p[10] = 42;
p = realloc(p, 200 * sizeof (int));  /* array length is now 200 */
printf("The answer is %d\n", p[10]); /* prints 42 */ 

Index