Course Content
C++ Introduction
0/1
C++ Variables & Constants
0/1
C++Scope of Variable
0/1
C++ Keywords & Identifiers
0/1
C++ Data Types
0/1
C++ Basic I/O
0/1
C++ Type Conversion
0/1
C++ Operators
0/1
C++ Comments
0/1
C++ If-else
0/1
C++ Ternary Operator
0/1
C++ for Loop
0/1
C++ Ranged for Loop
0/1
C++ while/do-while Loop
0/1
C++ break Statement
0/1
C++ Continue Statement
0/1
C++ switch Statement
0/1
C++ goto Statement
0/1
C++ Functions
0/1
C++ User-defined Functions
0/1
C++ Default Arguments
0/1
C++ Storage Class
0/1
C++ Recursion
0/1
C++ Return by Reference
0/1
C++ Arrays
0/1
C++ Multi-dimentional Arrays
0/1
C++ Arrays & Function
0/1
C++ String
0/1
C++ Structure
0/1
C++ Structure & Functions
0/1
C++ Pointers to Structure
0/1
C++ Pointers
0/1
C++ Void Pointers
0/1
C++ Pointers & Arrays
0/1
C++ Pointers & Functions
0/1
C++ Dynamic Memory Allocation
0/1
C++ OOPs Concepts
0/1
C++ Objects and Class
0/1
C++ Constructors
0/1
C++ Destructors
0/1
C++ Constructor Overloading
0/1
C++ Objects & Function
0/1
C++ Enumeration
0/1
C++ Inheritance
0/1
C++ Inheritance Access Control
0/1
C++ Inheritance Types
0/1
C++ Polymorphism
0/1
C++ Function Overloading
0/1
C++ Function Overriding
0/1
C++ Operator Overloading
0/1
C++ Friend Function
0/1
C++ Virtual Function
0/1
C++ Abstract Class & Pure Virtual Function
0/1
C++ Encapsulation
0/1
C++ Abstraction
0/1
C++ Templates
0/1
C++ Exception Handling
0/1
C++ Multithreading
0/1
C++ Standard Library
0/1
C++ Programming Tutorials
About Lesson

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.
Exercise Files
No Attachment Found
No Attachment Found
error: Content is protected !!