C++ Tutorial Index

C++ Tutorial C++ History C++ Installation C++ First Program C++ cin and cout C++ Data type C++ Variable C++ operator C++ Keywords

C++ Control Statements

C++ If C++ Nested if C++ If-else C++ If-else-if C++ Switch C++ Break C++ Continue C++ Goto C++ For loop C++ While loop C++ Do while loop

C++ Functions

C++ Call by Value C++ Call by Reference C++ Recursion Function C++ Inline function C++ Friend function

C++ Arrays

Single dimension array Two dimension array

C++ Strings

C++ Strings

C++ Inheritance

C++ Inheritance Single level Inheritance Multilevel Inheritance Multiple Inheritance Hierarchical Inheritance Hybrid Inheritance

C++ Polymorphism

C++ Polymorphism C++ Overloading C++ Overriding C++ Virtual Function

C++ Pointers

C++ Pointers C++ this pointer

C++ Exception Handling

C++ Exception Handling

C++ Constructors

C++ Constructors Default Constructor Parameterize Constructor Copy constructor Constructor Overloading Destructor

C++ File Handling

C++ File Handling C++ Writing to file C++ Reading file C++ Close file

Miscellaneous

C Vs C++ C++ Comments C++ Data Abstraction C++ Identifier C++ Memory Management C++ Storage Classes C++ Void Pointer C++ Array To Function C++ Expressions C++ Features C++ Interfaces C++ Encapsulation std::min in C++ External merge sort in C++ Remove duplicates from sorted array in C++ Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ C++ References C++ Friend Functions C++ Mutable keyword Unary Operators in C++ Initialize Array of objects with parameterized constructors in C++ Differences between #define & const in C/C++ C++ Program to Implement Shell Sort C++ Program to Implement Merge Sort Storage Classes in C Vector resize() in C++ Passing by Reference Vs. Passing by the pointer in C++ Free vs delete() in C++ goto statement in C and C++ C++ program to read string using cin.getline() C++ String Concatenation Heap Sort in C++ Swap numbers in C++ Input Iterators in C++ Fibonacci Series in C++ C ++ Program: Alphabet Triangle and Number Triangle C++ Program: Matrix Multiplication C++ Program to Print Fibonacci Triangle Stack in C++ Maps in C++ Queue in C++ C++ Bitset C++ Algorithms Priority Queue in C++ C++ Multimap C++ Deque Function Pointer in C++ Sizeof() Operators in C++ C++ array of Pointers free() Vs delete in C Timsort Implementation Using C++ CPP Templates C++ Aggregation C++ Enumeration C++ Math Functions C++ Object Class C++ Queue Initialize Vector in C++ Vector in C++ C++ STL Components Function overloading in C++ C++ Maximum Index Problem C++ find missing in the second array C++ Program to find the product array puzzle C++ Program To Find Largest Subarray With 0 Sum C++ Program To Move All Zeros To The End Of The Array C++ Program to find the element that occurs once C++ Program to find the largest number formed from an array Constructor Vs Destructor C++ Namespaces C++ OOPs Concept C++ Static C++ Structs C++ Try-Catch C++ User Defined Exceptions C++ Virtual Destructor C++ vs C# Malloc() and new in C++ Palindrome Number Program in C++ Snake Code in C++ Splitting a string in C++ Structure Vs Class in C++ Virtual Function Vs Pure Virtual Function C++ Bidirectional Iterators C++ Forward Iterators C++ Iterators C++ Output Iterators C++ Range-based For Loop Converting string into integer in C++ LCM Program in C++ Type conversion in C++ Add two numbers using the function in C++ Advantage and disadvantage friend function C++ Armstrong Number Program in C++ ATM machine program in C++ using functions Binary to Decimal in C++ Bit Manipulation in C++ C++ Constructor C++ Dijkstra Algorithm Using the Priority Queue C++ int into String C++ Signal Handling Decimal to Binary in C++ Decimal to Hexadecimal in C++ Decimal to Octal in C++ Factorial Program in C++ Function in C++ Hexadecimal to Decimal in C++ Octal to Decimal in C++ Reverse a Number in C++ Structure Vs Class in C++ C++ Forward Iterators C++ Output Iterators C++ Prime number program Constructor Overloading in C++ Different Ways to Compare Strings in C++ Program to convert infix to postfix expression in C++ SET Data Structure in C++ Upcasting and Downcasting in C++ Reverse an Array in C++ Fast Input and Output in C++ Delete Operator in C++ Copy elision in C++ C++ Date and Time C++ Bitwise XOR Operator Array of sets in C++ Binary Operator Overloading in C++ Binary Search in C++ Implementing the sets without C++ STL containers Scope Resolution Operator in C++ Smart pointers in C++ Types of polymorphism in C++

free() Vs delete in C

free() Vs delete in C++

free() function

The free() function in C++ is primarily used to dynamically deallocate the memory. It is a library-based function and is defined particularly in the stdlib.h header file and is used when the malloc() function is pointing to the memory or NULL pointer.

In other words, free() should only be used when the pointer is pointing using malloc() or a NULL pointer.

Syntax:   

free(pointer);

Here,

free = function to deallocate memory.

pointer = pointer of any data type.

Example:  int *pointer;

          free(pointer);

Let us now look through an example to see how free function works.

#include<bits/stdc++.h>

using namespace std;

int main ()

{

  int *object1, *object2, *object3;

                object1 = (int*) malloc (100*sizeof(int));

                object2 = (int*) calloc (100,sizeof(int));

                object3 = (int*) realloc (object2,500*sizeof(int));

                free (object1);

                free (object3);

  return 0;

}

Output:

1

Explanation:

This program returns nothing. It just shows the ways to allocate and deallocate memory using the free function. The malloc() and calloc() are used to demonstrate the functioning of free() in C++.

For reference, we must know that-

  1. malloc() : used to allocate memory(function)
  2. calloc():allocate and zero-initialize array(function)
  3. realloc() : reallocate memory block(function)

Note: If the pointer does not point to a block previously allocated with calloc(), malloc(), or realloc(), it is not a NULL pointer. It can cause undefined behavior.

Let’s look at another example with NULL pointers.

#include <iostream>

#include <cstdlib>

using namespace std;

int main()

{

                int y = 5;

                int *pointer1 = NULL;

                int *pointer2 = &y;

                if(pointer1)

                {

                                cout << "Pointer is not Null" << endl;

                }

                else

                {

                                cout << "Pointer is Null" << endl;

                }

                free(pointer1);

                cout << *pointer2;

                return 0;

}

Output:

2

Explanation:

In the above code, we have used a NULL pointer to show how the free function works in C++. We have not used calloc(), malloc(), or realloc() functions since we are using a NULL pointer. We have assigned an integer variable 'y' with value 5, two integer pointers, namely 'pointer1' and 'pointer2', and then assigned the address of variable 'y' to the pointer2, and the pointer1 is kept NULL. The next task is to check if the pointer1 is NULL or not. If pointer 1 is found NULL, then the output is printed as NULL, and the value of pointer2, which has a base address of y, is printed on the console.

‘delete’ keyword

In C++, the main function of the delete keyword is to destroy array or non-array(pointer) objects which are created by new expressions.

To understand the delete keyword in-depth, look at the following points:

  1. delete keyword is denoted either using delete operator or delete[] operator.
  • delete keyword deallocates the variable on heap memory which is dynamically allocated using a new keyword.
  • When the delete keyword is used, the object is not destroyed instead the value or memory pointed by the pointer is destroyed.
  • It does return value since the delete operator has a void return type.

Syntax:  

delete pointerVariable or pointer_name;

delete [] pointer;  (if it is an array)

Example:   delete *pointer1;

Let’s visualize it using coding examples.

#include<bits/stdc++.h>

using namespace std; 

int main() 

    int *pointer1; 

    pointer1=new int; 

    *pointer1=100; 

        cout << "Current Value : " <<*pointer1<<endl; 

    delete pointer1; 

        cout <<"Value after deletion : "  <<*pointer1<<endl; 

 return 0; 

Output:

3

Explanation:

In the above code, we have used the new operator to allocate the memory with the value 100. We already know that the delete operator is used to delete the memory block that is pointed by the pointer1, so we created a new variable that has an address of the block. The value after deletion is then printed on the console.

Let us see how the delete operator works with arrays in the coding example below.

#include<bits/stdc++.h>

using namespace std; 

int main() 

int *pointer1=new int[5];

cout << "Please enter five integers :" <<endl; 

    for(int i=1;i<=5;i++) 

    { 

        cin>>pointer1[i]; 

    cout << "The entered values are:" << endl; 

        for(int i=1;i<=5;i++) 

    { 

        cout<<*(pointer1+i)<<endl; 

    } 

    delete[] pointer1;

    cout << "After deleting the first value, we have :" <<endl; 

        for(int i=1;i<=5;i++) 

    { 

        cout<<*(pointer1+i)<<endl; 

 return 0; 

Output:

4

Explanation:

In the above code, we have constructed a pointer concerning an array that takes 5 elements like input and stores them. To do this, we looped over to take inputs one at a time and display them using consequently by using the second loop. The statement (*pointer+i) indicates that we are shifting the position of the pointer over the elements one by one. We know that while allocating memory, the pointer points to the address of the first element of the array, therefore the delete[] operator also deletes only the first element of the array and prints the rest on the console.



ADVERTISEMENT
ADVERTISEMENT