realloc()

We may need to resize the dynamically allocated memory in our C-program. Resizing can be done to increase as well as decrease the size of dynamically added memory. realloc is the system call that enables us to do the same.

Let us begin with understanding the syntax for the same

void* realloc (void* ptr, size_t size);

In the above function call

  • ptr is the pointer to dynamically allocated memory that we want to resize. If the memory pointed to by ptr is not dynamically allocated, then the behavior is undefined.
  • size is the new size of memory chunk that we want after reallocation. It can be larger or smaller than the size of originally allocated memory chunk.

realloc library function then does the following

    • it releases the memory pointed to by ptr
    • it allocates a new chunk of memory of size specified by input parameter size.
    • if the new memory chunk is smaller than the older one, then the content of the new memory chunk is identical to the content of older one till ‘size‘ bytes
    • if the new memory chunk is larger than the older one, then the content of the new memory chunk is identical to the content of older one till the size of old memory chunk. Any bytes beyond the size of old memory allocation have indeterminate values.
    • it returns the pointer to the newly allocated memory location. After this function call, ptr doesn’t represent a valid memory location as it is freed. Note that there is no need to explicitly free memory allocation pointed to by ptr in this case.

Let us consider an example which allocates a memory chunk to accommodate 10 integers. Then it reallocates it to accommodate 12 integers.

int main()
{
#define SIZE 10
#define NEW_SIZE 12
    int *ptr = (int *)malloc(sizeof(int)*SIZE);
    int index = 0;
    int *ptr_new = NULL;

    for (index = 0; index < SIZE; index ++) {
        *(ptr+index) = index*10;
    }

    ptr_new = (int *)realloc(ptr, sizeof(int)*NEW_SIZE);
    *(ptr_new + 10) = 255;
    *(ptr_new + 11) = 256;

    for(index = 0; index < NEW_SIZE; index++)
        printf(“%d “, *(ptr_new + index));
    free (ptr_new);
    return 0;
}

The output of above program is

0 10 20 30 40 50 60 70 80 90 255 256

Note the following in above program:

  1. After reallocation, the content of first 10 integers was restored.
  2. We did not free ptr, and only invoked free for ptr_new
  3. We declared two different variables for the purpose of explanation. We can very well reuse the variable ptr to store the return value of realloc library function.