What is a free function in C++?

C++Server Side ProgrammingProgramming

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.


#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 */


String = tutorialspoint, Address = 0x22fe38
String = tutorialspoint.com, Address = 0x22fe38
Updated on 30-Jul-2019 22:30:26