Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
#include <stdlib.h>
void free(void *ptr);
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.
Special behavior for C++: Under C++, you cannot use free() with an item that was allocated using the C++ new keyword.
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 */
}
else
{ /* Out of storage */
printf( "Error: out of storage\n" );
abort();
}
}