C++ dynamic memory

C++ dynamic memory

  • Knowing how dynamic memory works in C++ is essential to being a good C++ programmer. Memory in a C++ program is divided into two parts:

    • Stack: All variables declared inside a function will occupy stack memory.
    • Heap: This is unused memory in the program, which can be used to dynamically allocate memory while the program is running.
      In many cases, you cannot predict in advance how much memory is needed to store specific information in a defined variable, and the size of the required memory needs to be determined at runtime.
  • In C++, you can allocate memory on the heap at runtime for a variable of a given type using special operators, which return the address of the allocated space. This operator is the new operator.

  • If you no longer need the dynamically allocated memory space, you can use the delete operator to delete the memory previously allocated by the new operator.

  • Before introducing dynamic memory, let's talk about arrays and pointers.

1. Pointer

  • Let’s talk about the array first. An array is a collection of elements of the same type that can store a fixed size . The definition and initialization are as follows:
//定义大小为10的double类型数组,默认元素为0
double balance[10];

//***********初始化***************************
double balance[5]={
    
    1.,20.,3.,15.,6};

//或者省略大小,自动计算
double balance[]={
    
    1.,20.,3.,15.,6};

//数组值读取:
// 输出数组中每个元素的值                     
for ( int j = 0; j < 10; j++ )
{
    
    
     cout << balance[ j ] << endl;
}
 
 //多维数组
 int a[3][4] = {
    
      
 {
    
    0, 1, 2, 3} ,   /*  初始化索引号为 0 的行 */
 {
    
    4, 5, 6, 7} ,   /*  初始化索引号为 1 的行 */
 {
    
    8, 9, 10, 11}   /*  初始化索引号为 2 的行 */
};
//或者
int a[3][4] = {
    
    0,1,2,3,4,5,6,7,8,9,10,11};
  • Read array address:
int  var1;
char var2[10];
 
cout << "var1 变量的地址: ";
cout << &var1 << endl;
 
cout << "var2 变量的地址: ";
cout << &var2 << endl;

printf:

var1 变量的地址: 0xbfebd5c0
var2 变量的地址: 0xbfebd5b6
  • The function of the pointer is similar to that of the array, and it is also used as a collection of stored data. The difference is that the pointer is a variable, and its value is the address of another variable, that is, the direct address of the memory. It is defined as follows:
int    *ip;    /* 一个整型的指针 */
double *dp;    /* 一个 double 型的指针 */
float  *fp;    /* 一个浮点型的指针 */
char   *ch;    /* 一个字符型的指针 */

Use pointers to variables:

#include <iostream>
 
using namespace std;
 
int main ()
{
    
    
   int  var = 20;   // 实际变量的声明
   int  *ip;        // 指针变量的声明
 
   ip = &var;       // 在指针变量中存储 var 的地址
 
   cout << "Value of var variable: ";
   cout << var << endl;
 
   // 输出在指针变量中存储的地址
   cout << "Address stored in ip variable: ";
   cout << ip << endl;
 
   // 访问指针中地址的值
   cout << "Value of *ip variable: ";
   cout << *ip << endl;
 
   return 0;
}

printf:

Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
Value of *ip variable: 20

Use pointers to arrays:

#include <iostream>
 
using namespace std;
const int MAX = 3;
 
int main ()
{
    
    
   int  var[MAX] = {
    
    10, 100, 200};
   int  *ptr;
 
   // 指针中的数组地址
   ptr = var;
   for (int i = 0; i < MAX; i++)
   {
    
    
      cout << "var[" << i << "]的内存地址为 ";
      cout << ptr << endl;
 
      cout << "var[" << i << "] 的值为 ";
      cout << *ptr << endl;
 
      // 移动到下一个位置
      ptr++;
   }
   return 0;
}

printf:

var[0]的内存地址为 0x7fff59707adc
var[0] 的值为 10
var[1]的内存地址为 0x7fff59707ae0
var[1] 的值为 100
var[2]的内存地址为 0x7fff59707ae4
var[2] 的值为 200

2. Dynamic memory

2.1 new and delete operators

Use new to allocate memory:

double* pvalue  = NULL; // 初始化为 null 的指针
pvalue  = new double;   // 为变量请求内存

//检查
if( !(pvalue  = new double ))
{
    
    
   cout << "Error: out of memory." <<endl;
   exit(1);
 
}

The malloc() function has appeared in the C language, and it still exists in C++, but it is recommended not to use the malloc() function as much as possible.
The main advantage of new over the malloc() function is that new doesn't just allocate memory, it also creates objects.

At any time, when you feel that a variable that has dynamically allocated memory is no longer needed, you can use the delete operator to release the memory it occupies , as follows:

delete pvalue;        // 释放 pvalue 所指向的内存

2.2 Dynamic memory allocation of arrays

  • Allocate memory for character array
char* pvalue  = NULL;   // 初始化为 null 的指针
pvalue  = new char[20]; // 为变量请求内存
  • delete memory
delete [] pvalue;        // 删除 pvalue 所指向的数组
  • one-dimensional array
// 动态分配,数组长度为 m
int *array=new int [m];
 
//释放内存
delete [] array;
  • Two-dimensional array
int **array;
// 假定数组第一维长度为 m, 第二维长度为 n
// 动态分配空间
array = new int *[m];
for( int i=0; i<m; i++ )
{
    
    
    array[i] = new int [n];
}
//释放
for( int i=0; i<m; i++ )
{
    
    
    delete [] array[i];
}
delete [] array;
  • three-dimensional array
#include <iostream>
using namespace std;
 
int main()
{
    
       
    int i,j,k;   // p[2][3][4]
    
    int ***p;
    p = new int **[2]; 
    for(i=0; i<2; i++) 
    {
    
     
        p[i]=new int *[3]; 
        for(j=0; j<3; j++) 
            p[i][j]=new int[4]; 
    }
    
    //输出 p[i][j][k] 三维数据
    for(i=0; i<2; i++)   
    {
    
    
        for(j=0; j<3; j++)   
        {
    
     
            for(k=0;k<4;k++)
            {
    
     
                p[i][j][k]=i+j+k;
                cout<<p[i][j][k]<<" ";
            }
            cout<<endl;
        }
        cout<<endl;
    }
    
    // 释放内存
    for(i=0; i<2; i++) 
    {
    
    
        for(j=0; j<3; j++) 
        {
    
       
            delete [] p[i][j];   
        }   
    }       
    for(i=0; i<2; i++)   
    {
    
           
        delete [] p[i];   
    }   
    delete [] p;  
    return 0;
}

2.3 Dynamic memory allocation of objects

  • Define a structure object to test dynamic memory
#include <iostream>
using namespace std;
 
class Box
{
    
    
   public:
      Box() {
    
     
         cout << "调用构造函数!" <<endl; 
      }
      ~Box() {
    
     
         cout << "调用析构函数!" <<endl; 
      }
};
 
int main( )
{
    
    
   Box* myBoxArray = new Box[4];
 
   delete [] myBoxArray; // 删除数组
   return 0;
}

If you want to allocate memory for an array of four Box objects, the constructor will be called 4 times, and similarly, when these objects are deleted, the destructor will be called the same number of times (4 times).

When the above code is compiled and executed, it produces the following result:

调用构造函数!
调用构造函数!
调用构造函数!
调用构造函数!
调用析构函数!
调用析构函数!
调用析构函数!
调用析构函数!

Guess you like

Origin blog.csdn.net/yohnyang/article/details/129128653