Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library

The C++ <cstdlib> free() function is used to deallocate the space previously allocated by malloc(), calloc(), or realloc() functions.

If ptr is a null pointer, the function does nothing. If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior. The function does not change the value of ptr itself, hence it still points to the same (now invalid) location.


void free (void* ptr);


ptr Specify pointer to the memory to deallocate.

Return Value



The below example shows the usage of <cstdlib> free() function.

#include <cstdio>
#include <cstdlib>
int main (){
  int *p1 = (int*) calloc(5, sizeof(int));  
  int *p2 = (int*) malloc(sizeof(int[5]));
  int *p3 = (int*) realloc(p2, 10*sizeof *p3);

  //deallocating previously allocated memory
  return 0;

The above program gives no output and demonstrate the way to allocate and free dynamic memory using <cstdlib> library.

❮ C++ <cstdlib> Library