English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ Memory Management (new and delete)

In this article, you will learn to use new and delete operations in C ++effectively manage memory.

ArrayCan be used to store multiple data of the same type, but there are serious drawbacks to using arrays.

Memory should be allocated when declaring an array, but in most cases, the exact required memory can only be determined at runtime.

In this case, the best practice is to declare an array with the maximum possible required memory (declare an array expected to have the maximum possible size).

The downside is that unused memory is wasted and cannot be used by any other program.

To avoid wasting memory, you can in C ++operator and delete operator to dynamically allocate memory required at runtime.

Example1:C ++Memory Management

c++The program stores the grades of n students and displays them, where n is the number of students input by the user.

#include  <iostream>
#include  <cstring>
using  namespace  std;
int  main()
{
    int  num;
    cout  <<  "输入学生总数:  ";
    cin  >>  num;
    float* ptr;
    
    // Floating-point  numbers  allocated  for  memory
    ptr  =  new  float[num];
    cout  <<  "输入学生的成绩。"  <<  endl;
    for  (int  i  =  0;  i  <  num; ++i)
    {
        cout  <<  "学生"  <<  i + 1 <<  ":  ";
        cin  >> *(ptr + i);
    }
    cout  <<  "\n显示学生的成绩。"  <<  endl;
    for  (int  i  =  0;  i  <  num; ++i)  {
        cout  <<  "学生"  <<  i + 1 <<  "  :"  << *(ptr + i) << endl;
    }
    // ptr  memory  is  released
    delete  []  ptr;
    return 0;
}

Output results

Enter  the  total  number  of  students: 5
Enter  students'  grades.
Students1: 295
Students2: 485
Students3: 650
Students4: 700
Students5: 540
Display  students'  grades.
Students1 :295
Students2 :485
Students3 :650
Students4 :700
Students5 :540

in this program, only the memory required to dynamically declare storage for num (input by the user) floating-point numbers is declared.

new operator

ptr  =  new  float[num];

The expression in the above program returns a pointer to a portion of memoryPointeris exactly enough to contain num floating-point data.

delete operator

After allocating memory using the new operator, it should be released back to the operating system.

If the program uses new to occupy a large amount of memory, the system may crash because the operating system does not have available memory, leading to memory exhaustion.

The following expression releases memory back to the operating system.

delete  []  ptr;

Brackets [] indicate that the array has been deleted. If you need to delete a single object, you do not need to use brackets. For example:

delete  ptr;

Example2:C ++Memory Management

C ++Into handle the above program using an object-oriented approach.

#include  <iostream>
using  namespace  std;
class  Test
{
private:
    int  num;
    float *ptr;
public:
    Test()
    {
        cout  <<  "输入学生总数:  ";
        cin  >>  num;
        
        ptr  =  new  float[num];
        
        cout  <<  "输入学生的成绩。"  <<  endl;
        for  (int  i  =  0;  i  <  num; ++i)
        {
            cout  <<  "学生"  <<  i + 1 <<  ":  ";
            cin  >> *(ptr + i);
        }
    }
    
    ~Test() {
        delete[] ptr;
    }
    void  Display()  {
        cout  <<  "\n显示学生的成绩。"  <<  endl;
        for  (int  i  =  0;  i  <  num; ++i)  {
            cout  <<  "学生"  <<  i+1 <<  "  :"  << *(ptr + i) << endl;
        }
    }
    
};
int main() {
    Test s;
    s.Display();
    return 0;
}

The output of this program is the same as the output of the above program.

When the object s is created, the constructor is called, which allocates memory for num floating-point data.

The destructor is automatically called when the object is destroyed, that is, when the object goes out of scope.

    ~Test() {
        delete[] ptr;
    }

This destructor executes delete[] ptr; and returns the memory to the operating system.