You should use the standard library function realloc
. As the name suggests, it reallocates a block of memory. Its prototype is (contained in the header stdlib.h
)
void *realloc(void *ptr, size_t size);
The function changes the size of the memory block pointed to by ptr
to size
bytes. This memory block must have been allocated by a malloc
, realloc
or calloc
call. It is important to note that realloc
may extend the older block to size
bytes, may keep the same block and free the extra bytes, or may allocate an entirely new block of memory, copy the content from the older block to the newer block, and then free
the older block.
realloc
returns a pointer to the block of reallocated memory. If it fails to reallocate memory, then it returns NULL and the original block of memory is left untouched. Therefore, you should store the value of ptr
in a temp variable before calling realloc
else original memory block will be lost and cause memory leak. Also, you should not cast the result of malloc
- Do I cast the result of malloc?
// allocate memory for 10 integers
int *arr = malloc(10 * sizeof *arr);
// check arr for NULL in case malloc fails
// save the value of arr in temp in case
// realloc fails
int *temp = arr;
// realloc may keep the same block of memory
// and free the memory for the extra 5 elements
// or may allocate a new block for 5 elements,
// copy the first five elements from the older block to the
// newer block and then free the older block
arr = realloc(arr, 5 * sizeof *arr);
if(arr == NULL) {
// realloc failed
arr = temp;
}