×

Free vs delete() in C++

Free vs delete() in C++

In this section, we will learn about the free() function and also create a C ++ program of the delete operator.

What is free() Function in C++?

In C++, the free() function is used to dynamically de-allocate the memory. It is essentially a library feature used in C++ and is specified in the header file stdlib.h. This library function can be used when either the pointers refer to the allocated memory using malloc() or the Null pointer.

Syntax of free() function

Assume that we defined a 'ptr' pointer, and now we want its memory to be de-allocated:

free(ptr);        

The syntax above will de-allocate the pointer variable 'ptr' memory.

free() parameters

In the syntax above, ptr is a parameter within the function free(). The ptr is a pointer pointing towards the allocated memory block using malloc(), calloc() or realloc() feature. Even this pointer may be null or a pointer allocated using malloc but not referring to any other block of memory.

  • If the pointer is null, then the function free() will do nothing.
  • Unless the pointer is allocated using malloc, calloc, or realloc but does not point to any main memory, then this feature can trigger undefined behavior.

free() Return Value

The function free() refused to return any value. The key feature is memory free.

By an example, let’s understand.

#include <iostream> 
#include <cstdlib> 
using namespace std; 
int main() 
{ 
    int *ptr; 
    ptr = (int*) malloc(7*sizeof(int)); 
    cout << "Enter 7 integer" << endl; 
    for (int k=0; k<7; k++) 
    { 
    // *(ptr+k) can be replaced by ptr[k] 
        cin >>ptr[k]; 
    } 
    cout << endl << "user detail"<< endl; 
    for (int k=0; k<7; k++) 
    { 
        cout <<*(ptr+k)  << " "; 
    } 
    free(ptr); 
    /* prints a garbage value after ptr is free */ 
    cout << "Garbage Value" << endl; 
    for (int k=0; k<7; k++) 
    { 
        cout << *(ptr+k)<< " "; 
    } 
    return 0; 
}

The code above demonstrates how function free() works with malloc(). First, we define the integer pointer * ptr, and then we assign the memory to that pointer variable using malloc(). Now, ptr points to the uninitialized 7-integer memory block. We use the free() function after allocating the memory to delete this allocated memory.

Output:

Free vs delete() in C++

Example: malloc() and free()

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int s, k, *ptr, sum = 0;
    printf("Enter the amount of elements: ");
    scanf("%d", &s);
    ptr = (int*) malloc(s * sizeof(int));
    if(ptr == NULL)                    
    {
        printf("Error! memory not allocated.");
        exit(0);
    }
    printf("Enter elements: ");
    for(k = 0; k < s; ++k)
    {
        scanf("%d", ptr + k);
        sum += *(ptr + k);
    }
    printf("Sum = %d", sum);
    // deallocating the memory
    free(ptr);
    return 0;
}

Output:

Free vs delete() in C++

Example 3: realloc()

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int *ptr, k , s1, s2;
    printf("Enter size: ");
    scanf("%d", &s1);
    ptr = (int*) malloc(s1 * sizeof(int));
    printf("Addresses of previously allocated memory: ");
    for(k = 0; k < s1; ++k)
         printf("%u\n",ptr + k);
    printf("\nEnter the new size: ");
    scanf("%d", &s2);
    // rellocating the memory
    ptr = realloc(ptr, s2 * sizeof(int));
    printf("Addresses of newly allocated memory: ");
    for(k = 0; k < s2; ++k)
         printf("%u\n", ptr + k);
    free(ptr);
    return 0;
}

Output:

Free vs delete() in C++


Delete Operator

It is an operator used in programming language for C++, and it is used to dynamically de-allocate the memory. This operator is primarily used for the allocation of many references using a new operator or NULL pointer.

Syntax

delete pointer_name

For example, if we use the new operator to allocate the memory to the pointer, then we want to erase it now. We use the following statement to delete the Pointer:

delete p; 

Some significant delete operator related points are:

  • Either it is used to delete the array or non-array objects which are allocated using the new keyword.
  • We use delete [] and delete operator to delete the array or non-array object, respectively.
  • The latest keyword allocates the memory in a heap, and we can assume the delete operator must still deallocate the memory from the heap.
  • It does not destroy the pointer, but it destroys the value or the block of memory which the pointer points to.

Example of delete operator:

#include <iostream>
#include <string>
using namespace std;
int main()
 {
   int *ptr = NULL;
   ptr = new int();
   int *var = new int(11);
   if(!ptr)
   {
        cout<<"bad memory allocation"<<endl;
    }
   else
  {
       cout<<"memory allocated successfully"<<endl;
       *ptr = 6;
       cout<<"*ptr = "<<*ptr<<endl;
       cout<<"*var = "<<*var<<endl;
}
double *myarray = NULL;
myarray = new double[6];
if(!myarray)
 {cout<<"memory not allocated"<<endl;}
else
   {
     for(int j=0;j<6;j++)
       myarray[j] = j+1;
       cout<<"myarray values : ";
     for(int j=0;j<6;j++)
       cout<<myarray[j]<<"\t";
   }
delete ptr;
delete var;
delete[] myarray;
return 0;
}

Output:

Free vs delete() in C++

We have illustrated the use of new and delete operators in the example of the code above. We used the "new" operator to allocate memory for a variable, arrays, and also initialize a value for another variable. Then we use delete operator to delete these entities.


Related Topics

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

How to Reverse a String in C++ using For Loop

For Loop: We may loop through a certain section of C++ code repeatedly using the for loop. A for loop is carried out if the test expression yields a true result. The...

4 minutes read.

Message Passing in C++

The act of sending and receiving information by an object is referred to as communication, and all communication between objects that takes place via message is known as message passing....

1 minute read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

Lexicographically Next Permutation in C++

In this tutorial, we'll look at how to use C++ to generate the lexicographically next permutation of a string. The lexicographically next permutation is the larger permutation. "ACB," for example,...

3 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

How to improve programming skills in C++

Before getting started, one should know why to improve their programming skills. To become a good software developer or programmer, one must be skilled in at least one programming language. Many...

4 minutes read.

C++ Program to Implement Shell Sort

    C++ Program to Implement Shell Sort shell sort is basically an Insertion Sort variant. In the insertion sort, we only transfer elements ahead of one location. Many movements are involved...

2 minutes read.

Decimal to Octal in C++

We must create a software that converts a decimal number into an equal octal number given a decimal number as input i.e. convert a number having a base value of...

3 minutes read.

Auto keyword in C++

The primary function of auto keyword is to assign and detect the value of the data type automatically in C++. The compiler knows the data type of the variable by...

2 minutes read.

C++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than...

4 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

How the value is passed in C++

Introduction: The call-by-value method of giving arguments to a function duplicates the real value of an argument into the formal parameter of the function. In this instance, modifications to the parameter...

5 minutes read.

LCM Program in C++

What is LCM? LCM is an acronym for "least common multiple". It is used to discover the lowest positive integer divisible by all integers (whose LCM is calculated). For instance, the...

4 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.