CSPP50101 - Lab 10

Calling realloc() to resize a block of memory

For some problems, you may want to increase the size of a block of memory that has already been allocated with malloc(). For example, suppose you want to double the size of a dynamically allocated array of integers to store more data. One approach (shown below) would be to allocate a new block of memory with malloc(), copy data from the original array, and then free the original array:
    /* Allocate original array */
    int * pi;
    if((pi = (int*)malloc( INIT_SZ * sizeof(int))) == NULL)
    {
      /* Error handling */
      return NULL;
    }
  
    ...
 

    /* Allocate larger block of memory */
    int * new;
    if((new = (int*)malloc(2 * INIT_SZ * sizeof(int))) == NULL)
    {
      /* Error handling */
      free(pi);
      return NULL;
    }

    /* Copy data from original array */
    memcpy(new, pi, INIT_SZ*sizeof(int));

    /* Free original array */
    free(pi);

    /* Update pointer variable pi */
    pi = new;    
A more concise way to do this is to call the stdlib.h function realloc(), which resizes a block of memory that has already been dynamically allocated:
    /* Allocate original array */
    int * pi;
    if((pi = (int*)malloc( INIT_SZ * sizeof(int))) == NULL)
    {
      /* Error handling */
      return NULL; 
    }

    ...

    /* Resize original array: double size */
    int * tmp ;
    if((tmp = (int*)realloc( pi, 2 * INIT_SZ * sizeof(int))) == NULL )
    {
      /* Error handling */
      free(pi);
      return NULL;  
    }
    pi = tmp;
Here, the first argument to realloc() is the block to be resized, and the second argument is the requested size. realloc() returns a pointer to the new block of memory, which may or may not be the same address as the original pointer pi. If the pointers are different, then realloc() will automatically free pi and copy data into the new block of memory.

Like malloc(), realloc() will fail and return NULL if there is not enough memory available to complete the request. This means that you need to be careful when you overwrite the address of the original array. In this example, the value of pointer pi would be lost if this call to realloc() fails:

    /* Resize original array: double size */
    pi = (int*)realloc(pi, 2 * (*p_size) * sizeof(int))
For this reason, it is a good idea to save the return value of realloc() into a temporary variable before you overwrite the original pointer, as shown above with the use of variable tmp.

Type man 3 malloc at the command line for more information on malloc() and realloc().


BACK