C++ Standard Library C++ STL Library

C++ <cstdlib> - free() Function



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.

Syntax

void free (void* ptr);

Parameters

ptr Specify pointer to the memory to deallocate.

Return Value

None.

Example:

The example below 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
  free(p1);
  free(p3);
  return 0;
}

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


❮ C++ <cstdlib> Library