CITS2002 Systems Programming  
prev
CITS2002 CITS2002 schedule  

Reallocating previously allocated memory

We'd already seen that it's often the case that we don't know our program's memory requirements until we run the program.

Even then, depending on the input given to our program, or the execution of our program, we often need to allocate more than our initial "guess".

The C11 standard library provides a function, named realloc() to grow (or rarely shrink) our previously allocate memory:

extern void *realloc( void *oldpointer, size_t newsize );

We pass to realloc() a pointer than has previously been allocated by malloc(), calloc(), or (now) realloc().
Most programs wish to extend the initially allocated memory:

#include <stdlib.h>

  int  original;
  int  newsize;
  int  *array;
  int  *newarray;

  ....
  array = malloc( original * sizeof(int) );  
  if(array == NULL) {
      // HANDLE THE ALLOCATION FAILURE
  }
  ....

  newarray = realloc( array, newsize * sizeof(int) );
  if(newarray == NULL) {
      // HANDLE THE ALLOCATION FAILURE
  }
  ....

#include <stdlib.h>

  int  nitems = 0;
  int  *items = NULL;

  ....
  while( fgets(line ....) != NULL ) {
      items = realloc( items, (nitems+1) * sizeof(items[0]) );
      if(items == NULL) {
              // HANDLE THE ALLOCATION FAILURE
      }
      ....    // COPY OR PROCESS THE LINE JUST READ
      ++nitems;
  }
  ....
  if(items != NULL) {
      free( items );
  }

Of note:
  • if realloc() fails to allocate the revised size, it returns the NULL pointer.
  • if successful, realloc() copies any old data into the newly allocated memory, and then deallocates the old memory.
  • if the new request does not actually require new memory to be allocated, realloc() will usually return the same value of oldpointer.
  • a request to realloc() with an "initial" address of NULL, is identical to just calling malloc().

 


CITS2002 Systems Programming, Lecture 12, p10, 28th August 2024.