What is free Function in C?

The free() function in C library allows you to release or deallocate the memory blocks which are previously allocated by calloc(), malloc() or realloc() functions. It frees up the memory blocks and returns the memory to heap. It helps freeing the memory in your program which will be available for later use.

In C, the memory for variables is automatically deallocated at compile time. For dynamic memory allocation in C, you have to deallocate the memory explicitly. If not done, you may encounter out of memory error.

free() Syntax:

void free(void *ptr)

Here, ptr is the memory block that needs to be deallocated.

Now, let's learn how to use function of free in C language with an example.

free() in C Example:

#include <stdio.h>
int main() {
int* ptr = malloc(10 * sizeof(*ptr));
if (ptr != NULL){
  *(ptr + 2) = 50;
  printf("Value of the 2nd integer is %d",*(ptr + 2));
}
free(ptr);
}

Output of the above free in C example:

 Value of the 2nd integer is 50

 

YOU MIGHT LIKE: