How to use free() in C++

In C++, we can use the free() function to deallocate a memory block, making it available for further allocations.

The memory can be allocated beforehand using the calloc(), malloc(), or realloc() functions. It does not change the value of the pointer and points to the exact memory location.

Syntax

void free(void* ptr);

ptr

  • This represents the pointer to an allocated memory block.

  • If ptr is null, free() does nothing.

  • If ptr is not pointing to an allocated memory block, free() causes undefined behavior.

Return value

  • The function free() returns None.

Required headers

The function free() requires the following header to work properly:

#include <cstdlib>

Code

//Including headers
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
//Allocating memory block
int* ptr = (int*)calloc(3, sizeof(int));
int* ptr1 = (int*)malloc(3*sizeof(int));
int* ptr2;
ptr2 = (int*)realloc(ptr2,3*sizeof(int));
//Deallocating allocated memory
free(ptr);
free(ptr1);
free(ptr2);
return 0;
}

Free Resources