C/C++ memory management--stack area, heap area, data area, code area

A very nice article!

In the computer system, running program A will open up program A's memory area 1 in the memory, and running program B will open up program B's memory area 2 in the memory, and memory area 1 and memory area 2 are logically separated.
insert image description hereinsert image description here
The memory area 1 opened up in program A will be divided into several areas, which are the four areas of memory, and the four areas of memory are divided into stack area, heap area, data area and code area.

  • The stack area refers to the area where some temporary variables are stored. Temporary variables include local variables, return values, parameters, return addresses, etc. When these variables exceed the current scope, they will be automatically popped up. The maximum storage of the stack has a size, and this value is fixed, and exceeding this size will cause stack overflow.

  • The heap area refers to a relatively large memory space, which is mainly used for the allocation of dynamic memory; in program development, it is generally the developer who allocates and releases it. If it is not released at the end of the program, the system will automatically recycle it.

  • The data area refers to the area that mainly stores global variables, constants and static variables, and the data area can be divided into global area and static area. Global variables and static variables will be stored in this area.

  • The code area is easier to understand. It mainly stores executable code, and the attributes of this area are read-only.

malloc、free、new、deleteAll written in great detail. . Read the big guy's article



deletedelete[]forgot the difference with

class A
   {
    
    
    private:
      char *m_cBuffer;
      int m_nLen;

   `` public:
      A(){
    
     m_cBuffer = new char[m_nLen]; }
      ~A() {
    
     delete [] m_cBuffer; }
   };

   A *a = new A[10];
   delete a;         //仅释放了a指针指向的全部内存空间 但是只调用了a[0]对象的析构函数 剩下的从a[1]到a[9]这9个用户自行分配的m_cBuffer对应内存空间将不能释放 从而造成内存泄漏
   delete[] a;      //调用使用类对象的析构函数释放用户自己分配内存空间并且   释放了a指针指向的全部内存空间

Guess you like

Origin blog.csdn.net/weixin_44119881/article/details/112203990