Site icon DataFlair

Dynamic Memory Allocation in C++ | How new & delete Operator works

dynamic memory allocation c++

Free C++ course with real-time projects Start Now!!

Have you ever thought, how memory is allocated during the run time of a program? How can we determine the amount of memory that will be used in a program? Don’t worry we have the answer to all such questions. All this is done with the help of Dynamic Memory Allocation in C++.

DMA in C++ allows us to allocate memory to storage components of our program at run-time. It is one of the most significant features of C++. This tutorial will give you complete details of how DMA works, what is dangling pointer, and memory leak in C++.

Dynamic Memory Allocation in C++

C++ Dynamic Memory Allocation is different from that seen in the C. While C uses functions like malloc(), calloc(), realloc() and free() to handle operations based on DMA, C++ also uses all the 4 functions in addition to 2 different operators called new and delete to allocate memory dynamically.

These statements are indicative of the fact that DMA is implemented by the programmer itself. C++ lacks the feature of a garbage collector which automatically helps to free up unnecessary memory space occupied by stagnant garbage values.

It is important to note that the memory is dynamically allocated on the Heap. The non-static memory and local variables get memory allocated on Stack.

Now, let us try to understand the memory map of C++

From the above diagram, it is evident that there are 4 distinct regions of memory in C++.

1. Program: This region holds the compiled code of the program. Here, all the functions of the program start at a specific address.

2. Global variables: In this region, global variables are stored during the entire lifetime of the program.

3. Stack: This region is responsible for storing the return addresses at function calls, arguments passed to a function as well as local variables. It is important to note that local variables remain in the computer memory as long as the function continues. Soon as the function ceases, memory is erased from the stack. In addition to all this, the stack is also responsible for storing the current state of the CPU.

4. Heap: In this region, there is an abundance of free memory chunks that are allocated with the help of DMA.

Significance of Dynamic Memory Allocation in C++

Dynamic memory allocation is quite different from what the C++ compiler reserves for variables of fixed length. The implementation of DMA proves to be pretty flexible for the programmer. The user is free to allocate and deallocate memory as and when required. Moreover, with the help of DMA, you can create linked lists, dynamic stacks, queues, trees, etc.

For variables with statically allocated memory, such as int names[10], the C++ compiler reserves (4 x 10) bytes of memory which is fixed, that is, it cannot be altered. It is evident that C++ dynamic memory allocation provides immense flexibility to the user when the size of a particular variable is not known beforehand.

Dangling Pointer in C++

A pointer that points to the memory address of an object that has already been deleted is known as a dangling pointer in C++.

Here, the dangling pointer points to no value as 10 has already been deleted.
This happens when the object is destroyed in the program, that is when we delete or deallocate an object reference.

Memory Leak in C++

Whenever any mismanagement arises while allocation and deallocation of memory, memory leaks occur. One of the major drawbacks of C++ is that it does not have an automatic garbage collector like that seen in Java and Python. Due to the absence of this feature, memory is not efficiently managed and hence memory leaks occur. After the use of a pointer, it must be deallocated by the user manually, otherwise, it would hamper the other tasks at hand.

new Operator in C++

The new operator in C++ indicates a request for memory allocation on the Heap of the computer memory.

If the Heap has enough memory available in that region, then with the help of the “new” operator, you can initialize the memory and return the address of the newly allocated and initialized computer memory to the pointer variable.

After understanding what the new operator is and what it does, let us proceed with our discussion by trying to understand its syntax which is quite simple to grasp.

Declaration of new Operator

This is how the “new” operator allocates memory to the pointer.

pointer_variable = new data_type;

Another way of using the new keyword is;

data_type *pointer_variable = new data_type;

Here, pointer_variable is a pointer of data_type data-type. It can be of any built-in or user-defined data types like arrays, structure, and class.

For instance,

int *pointer = NULL;
pointer = new int;

or

int *pointer = new int;

Initialization of new Operator

The general way of initializing memory dynamically is:

pointer_variable = new data_type(value);

For instance,

int *ipointer = new int(10);
float *fpointer = new float(71.5);
char *cpointer = new char(‘x’);

Allocation of new Opewrator

The general way of initializing memory dynamically is:

pointer_variable = new data_type [size];

For instance,

int *pointer = new int [ 5 ]

delete Operator in C++

We use the “delete” operator in C++ for dynamic memory deallocation. Just like the “new” operator, the “delete” operator is also used by the programmer to manage computer memory.

Key takeaway: Both new and delete operators go hand in hand.

Syntax

delete pointer_variable;

For instance,

delete pointer;

Example of new and delete Operator in C++

After developing an understanding of the “new” and “delete” operations, it is the time to thoroughly understand it with the help of a C++ program.

#include <iostream> 
using namespace std; 

int main () 
{ 

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

int* ipointer = NULL; 

ipointer = new(nothrow) int; 
if (!ipointer) 
cout << "Cannot allocate memory dynamically!"<<endl; 
else
{ 
*ipointer = 10; 
cout << "The value of the integer pointer is: " << *ipointer << endl; 
} 

float *fpointer = new float(15.63); 

cout << "The value of the float pointer is: " << *fpointer << endl; 

int n = 10; 
int *pointer = new(nothrow) int[n]; 

if (!pointer) 
cout << "Cannot allocate memory dynamically!"<<endl; 
else
{ 
for (int i = 0; i < n; i++) 
pointer[i] = i+1; 

cout << "The values stored dynamically are: "<<endl;
for (int i = 0; i < n; i++) 
cout << pointer[i] << endl;
}

delete ipointer; 
delete fpointer; 
delete[] pointer; 

return 0; 
}

 

Output-

Quiz on Dynamic Memory Allocation in C++

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    What is the output of following program?

    #include <iostream>

    using namespace std;

      

    int main ()

    {

     

        int* p = NULL;

        p = new(nothrow) int;

        if (!p)

            cout << “allocation failed”;

        else

        {

            cout<<“allocated Passed”;

        }

    }

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    What is the output of following program?

    #include <iostream>

    using namespace std;

      

    int main ()

    {

        int* q = NULL;

        q = new(nothrow) int;

        if (q)

        {

            *q = 10;

            cout << *q << endl;

        

        }

    }

     

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    What is the output of following program?

    #include <iostream>

    using namespace std;

      

    int main ()

    {

        float *q = new float(50.5);

      

        cout<<*q;

    }

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    What is the output of following program?

    int main ()

    {

        int n = 3;

        int *p = new(nothrow) int[n];

        for (int i = 0; i < n; i++)

            p[i] = i+1;

     

        for (int i = 0; i < n; i++)

            cout << p[i] << ” “;

        return 0;

    }

     

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    What is the output of following program?

    #include <iostream>

    using namespace std;

      

    int main ()

    {

        int n = 3;

        char *p = new(nothrow) char[n];

        for (int i = 0; i < n; i++)

            p[i] = 65+i;

     

        for (int i = 0; i < n; i++)

            cout << p[i] << ” “;

        return 0;

    }

     

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

    What is the output of following program?

    #include <iostream>

    using namespace std;

      

    int main ()

    {

        int n = 3;

        char *p = new(nothrow) char[n];

        for (int i = 0; i < n; i++)

            p[i] = ‘Z’;

     

        for (int i = 0; i < n; i++)

            cout << p[i] << ” “;   

        return 0;

    }

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    What is the output of following program?

    #include <iostream>

    using namespace std;

    int main ()

    {

        int n = 3;

        char *p = new(nothrow) char[n];

        for (int i = 0; i < n; i++)

            p[i] = ‘Z’;

     

        for (int i = 0; i < n; i++)

            cout << p[i] << ” “;

        delete p[];    

        return 0;

    }

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

    What is the output of following program?

    #include <iostream>

    using namespace std;

     

    int main ()

    {

        int n = 3;

        char *p = new(nothrow) char[n];

        for (int i = 0; i < n; i++)

            p[i] = ‘Z’;

     

        for (int i = 0; i < n; i++)

            cout << p[i] << ” “;

        delete []p;    

        return 0;

    }

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

    What is the output of following program?

    #include <iostream>

    using namespace std;

      

    int main ()

    {

        long *q = new long(500);

        cout<<*q;

        delete q;

    }

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    What is the output of following program?

    #include <iostream>

    using namespace std;

      

    int main ()

    {

        long *q = new long(500);

        delete q;

        cout<<*q;

    }

     

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

    Which among the following is not a part of memory  in C++ program?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

    Where do the variables declared in the function take memory?

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

    Which among the following is the unused memory that can be used for dynamic allocation?

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    Which operator is used to clear the dynamic allocated memory?

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

     What operator is used to allocate dynamic memory?

    Correct
    Incorrect

Summary

Now you’re well familiar with the Dynamic Memory allocation in C++. You got all the answers like, how memory is allocated into the Heap, and how it proves to be of tremendous importance in C++ programming. At last, you are very well aware of memory leak and dangling pointer in C++.

If you’re still confused about the concept or finding any type of difficulties, then let us know in the comment section. Our experts will assist with your confusion.

Exit mobile version