Loading...
C++ Memory Management (dma): new and delete

C++ Memory Management (dma): new and delete

In this tutorial, we will learn Dynamic Memory Allocation and how to manage memory effectively in C++ using new and delete operations with the help of examples.

Memory Management

  • Memory management is a process of managing computer memory, assigning the memory space to the programs to improve the overall system performance.
  • C++ allows us to allocate the memory of a variable or an array in run time. This is known as "dynamic memory allocation".
  • In C++, we need to deallocate the dynamically allocated memory manually after we have no use for the variable.
  • In other programming languages such as Java and Python, the compiler automatically manages the memories allocated to variables. But this is not the case in C++.

Why is memory management required ?

  • As we know that arrays store the homogeneous data, so most of the time, memory is allocated to the array at the declaration time.
  • Sometimes the situation arises when the exact memory is not determined until runtime.
  • To avoid such a situation, we declare an array with a maximum size, but some memory will be unused.
  • To avoid the wastage of memory, we use the new operator to allocate the memory dynamically at the run time.

How is Memory allocated/deallocated ?

  • C language uses malloc() and calloc() function to allocate memory dynamically at run time and uses free() function to free dynamically allocated memory.
  • C++ supports these functions and also has two operators new and delete that perform the task of allocating and freeing the memory in a better and easier way.
  • We can allocate and then deallocate memory dynamically using the new and delete operators respectively.

This Tutorial is all about new and delete operators.


C++ new Operator

  • The new operator allocates memory to a variable.
  • The new operator denotes a request for memory allocation on the Free Store.
  • If sufficient memory is available, new operator initializes the memory and returns the address of the newly allocated and initialized memory to the pointer variable.

Syntax

To allocate memory of any data type, we can see that the syntax for using the new operator is

pointer_variable = new data-type;

The above syntax is used to create the object using the new operator. In the above syntax, 'pointer_variable' is the name of the pointer variable, 'new' is the operator, and 'data-type' defines the type of the data.

For example,

// declare an int pointer
int* ptVar;

// dynamically allocate memory
// using the new keyword 
ptVar = new int;

// assign value to allocated memory
*pttVar = 2;

Here, we have dynamically allocated memory for an int variable using the new operator.

Notice that we have used the pointer ptVar to allocate the memory dynamically. This is because the new operator returns the address of the memory location.

In the case of an array, the new operator returns the address of the first element of the array.


delete Operator

  • Since it is programmer’s responsibility to deallocate dynamically allocated memory, programmers are provided delete operator by C++ language.
  • Once we no longer need to use a variable that we have declared dynamically, we can deallocate the memory occupied by the variable.
  • For this, the delete operator is used. It returns the memory to the operating system. This is known as memory deallocation.

The syntax for this operator is

delete pointer-variable;

Here, pointer-variable is the pointer that points to the data object created by new.

Consider the code:

// declare an int pointer
int* ptVar;

// dynamically allocate memory for an int variable 
ptVar = new int;

// assign value to the variable memory
*ptVar = 2;

// print the value stored in memory
cout << *ptVar; // Output: 2

// deallocate the memory
delete ptVar;

Here, we have dynamically allocated memory for an int variable using the pointer ptVar.

After printing the contents of ptVar, we deallocated the memory using delete.

Note: If the program uses a large amount of unwanted memory using new, the system may crash because there will be no memory available for the operating system. In this case, the delete operator can help the system from crash.


Example 1: C++ Program to illustrate Dynamic Memory Allocation

// program to illustrate dynamic allocation and deallocation of memory using new and delete
#include <iostream>
using namespace std;

int main() {
    // declare an int pointer
    int* pInt;

    // declare a float pointer
    float* pFloat;

    // dynamically allocate memory
    pInt = new int;
    pFloat = new float;

    // assigning value to the memory
    *pInt = 2;
    *pFloat = 2.24f;

    cout << *pInt << endl;
    cout << *pFloat << endl;

    // deallocate the memory
    delete pInt, pFloat;

    return 0;
}

Output

2
2.24

In this program, we dynamically allocated memory to two variables of int and float types. After assigning values to them and printing them, we finally deallocate the memories delete.

  • Note: Dynamic memory allocation can make memory management more efficient.
  • Especially for arrays, where a lot of the times we don't know the size of the array until the run time.

Example 2: C++ Program to use new and delete Operators for Arrays

To print the content of a void pointer, we use the static_cast operator. It converts the pointer from void* type to the respective data type of the address the pointer is storing:

// C++ Program to store GPA of n number of students and display it
// where n is the number of students entered by the user

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    int number;
    cout << "Enter total number of students: ";
    cin >> number;
    float* p;
    
    // memory allocation of num number of floats
    p = new float[number];

    cout << "Enter GPA of students." << endl;
    for (int i = 0; i < number; ++i) {
        cout << "GPA of Student " << i + 1 << ": ";
        cin >> *(p + i);
    }

    cout << "\nDisplay The GPA of students." << endl;
    for (int i = 0; i < number; ++i) {
        cout << "GPA of Student " << i + 1 << " :" << *(p + i) << endl;
    }

    // ptr memory is released
    delete [] p;

    return 0;
}

Output

Enter total number of students: 4
Enter GPA of students.
GPA of Student 1: 4.8
GPA of Student 2: 4.3
GPA of Student 3: 4.7
GPA of Student 4: 3.7

Displaying GPA of students.
GPA of Student 1 :4.8
GPA of Student 2 :4.3
GPA of Student 3 :4.7
GPA of Student 4 :3.7

Working

  • In this program, we have asked the user to enter the number of students and store it in the num variable.
  • Then, we have allocated the memory dynamically for the float array using new.
  • We enter data into the array (and later print them) using pointer notation.
  • After we no longer need the array, we deallocate the array memory using the codedelete [] p;.
  • Notice the use of [] after delete. We use the square brackets [] in order to denote that the memory deallocation is that of an array.

Example 3: Program to use new and delete Operators for Objects

// program to store age of student in the object and display it.
#include <iostream>
using namespace std;

class Student {
    int age;
   public:
    Student() : age(20) {} // constructor initializes age to 20

    void getAge() {
        cout << "Age of Student = " << age << endl;
    }
};
int main() {

    // dynamically declare Student object
    Student* p = new Student();

    // call getAge() function
    p->getAge();

    // p memory is released
    delete p;

    return 0;
}

Output

Age of Student = 20

Working

  • In this program, we have created a Student class that has a private variable age.
  • We have initialized age to 20 in the default constructor Student() and print its value with the function getAge().
  • In main(), we have created a Student object using the new operator and use the pointer ptr to point to its address.
  • The moment the object is created, the Student() constructor initializes age to 20.
  • We then call the getAge() function using the code:
    p->getAge();
  • Notice the arrow operator ->. This operator is used to access class members using pointers.

Next Tutorial

We hope that this tutorial helped you develop better understanding of the concept of Dynamic Memory Allocation in C++.

Keep Learning : )

In the next tutorial, you'll learn about C++ OOPs Concept.

- Related Topics