CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Deallocating memory with free

In programs that:

  • run for a long time
    (perhaps long-running server programs such as web-servers), or
  • temporarily require a lot of memory, and then no longer require it,

we should deallocate the memory provided to us by malloc() and calloc().

The C11 standard library provides an obvious function to perform this:

extern void free( void *pointer );

Any pointer successfully returned by malloc() or calloc() may be freed.

Think of it as requesting that some of the allocated heap memory be given back to the operating system for re-use.

#include <stdlib.h>

    int   *vector = randomints( 1000 );

    if(vector != NULL) {
        // USE THE vector
        ......
        free( vector );
    }

Note, there is no need for your programs to completely deallocate all of their allocated memory before they exit - the operating system will do that for you.

 


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