C++ cstdlib free


The C++ <cstdlib> free function frees the memory allocated in heap.The declaration of the function is shown below.

void free(void *ptr);

Parameters:
void* -A pointer to the memory allocated in heap.

Return type
void

Some points to note:

i) You must always call this function whenever you have called the calloc , malloc or realloc functions.These functions allocate memory in heap and only the ‘free’ function can deallocate them.Forgetting to call the ‘free’ function will produce memory leakage in your program.

ii) If the ‘ptr’ points to NULL nothing happens.

iii) If the memory has been freed and we try to delete it again,in such case the behavior is undefined.

LinK: C++ cstdlib calloc function

Code example

void *mem=calloc( 3 , sizeof(char) );

memcpy( mem , “Babby” , 3 );

cout<< *(static_cast<char*>(mem))
<< *(static_cast<char*>(mem+1))
<< *(static_cast<char*>(mem+2)) ;

free(mem); ///necessary

Output in

Bab





Here is a more exhaustive code example utilizing the ‘free’ function.

#include <iostream>
#include <cstdlib>

using namespace std;

int main( )
{
int *imem ;
{
imem=(int*)malloc( sizeof(int)*3 ); //allocate memory to store 3 integers

if( imem!=NULL ) ///true if the allocation is successful
{
*imem=90 ;
*(imem+1)=100 ;
}
else
  cout<< “Memory allocation failed “;

free( imem ); ///memory deleted
}

free( imem ); ///behavior undefined

cin.get( );
return 0;
}

The ‘malloc’ function allocate memory in the heap.The arguments passed is the number of bytes the memory is allocated.

Link : C++ cstdlib malloc