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
ptrisnull,free()does nothing. -
If
ptris not pointing to an allocated memory block,free()causes undefined behavior.
Return value
- The function
free()returnsNone.
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 blockint* ptr = (int*)calloc(3, sizeof(int));int* ptr1 = (int*)malloc(3*sizeof(int));int* ptr2;ptr2 = (int*)realloc(ptr2,3*sizeof(int));//Deallocating allocated memoryfree(ptr);free(ptr1);free(ptr2);return 0;}