What is a free function in C++?


The C/C++ library function void free(void *ptr) deallocates the memory previously allocated by a call to calloc, malloc, or realloc. Following is the declaration for free() function.

void free(void *ptr)

This function takes a pointer ptr. This is the pointer to a memory block previously allocated with malloc, calloc or realloc to be deallocated. If a null pointer is passed as argument, no action occurs.

Example

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main () {
   char *str;
   /* Initial memory allocation */
   str = (char *) malloc(15);
   strcpy(str, "tutorialspoint");
   cout << "String = "<< str <<", Address = "<< &str << endl;
   /* Reallocating memory */
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   cout << "String = "<< str <<", Address = "<< &str << endl;
   /* Deallocate allocated memory */
   free(str);
   return(0);
}

Output

String = tutorialspoint, Address = 0x22fe38
String = tutorialspoint.com, Address = 0x22fe38

Updated on: 30-Jul-2019

252 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements