free() — Free a block of storage


Standards / Extensions C or C++ Dependencies

Single UNIX Specification, Version 3



#include <stdlib.h>

void free(void *ptr);

General description

Frees a block of storage pointed to by ptr. The ptr variable points to a block previously reserved with a call to calloc(), malloc(), realloc(), or strdup(). The number of bytes freed is the number of bytes specified when you reserved (or reallocated, in the case of realloc()), the block of storage. If ptr is NULL, free() simply returns without freeing anything. Since ptr is passed by value free() will not set ptr to NULL after freeing the memory to which it points.

This function is also available to C applications in a stand-alone System Programming C (SPC) Environment.
Note: Attempting to free a block of storage not allocated with calloc(), malloc(), realloc(), strdup(), or previously freed storage, can affect the subsequent reserving of storage and lead to an abend.

Special behavior for C++: Under C++, you cannot use free() with an item that was allocated using the C++ new keyword.

Returned value

free() returns no values.


/* This example illustrates the use of calloc() to allocate storage for x
   array elements and then calls free() to free them.
#include <stdio.h>
#include <stdlib.h>

int main(void)
  long * array;    /* start of the array */
  long * index;    /* index variable     */
  int    i;        /* index variable     */
  int  num;        /* number of entries of the array */

  printf( "Enter the size of the array\n" );
  scanf( "%i", &num );

  /* allocate num entries */
  if ( (index = array = (long *)calloc( num, sizeof( long ))) != NULL )
    ⋮   /*  do something with the array  */
    free( array );                        /* deallocates array  */
  { /* Out of storage */
    printf( "Error: out of storage\n" );