What is free Function in C?

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

The free() function is called to release/deallocate memory. By freeing memory in your program, you make more available for use later.

Syntax

void free(void *ptr)

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

For 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

 Value of the 2nd integer is 50

 

YOU MIGHT LIKE: