C Standard Library

C <stdlib.h> - free() Function



The C <stdlib.h> 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 <stdlib.h> free() function.

#include <stdio.h>
#include <stdlib.h>
 
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 <stdlib.h> library.


❮ C <stdlib.h> Library