Article Directory
1. Memory partition model
C++ program divides the memory into 4 areas during operation
- Code area: store the binary code of the function body, managed by the operating system
- Global area: store global variables and static variables and constants
- Stack area: automatically allocated by the compiler, storing function parameter values and local variables, etc.
- Heap area: allocated and released by the programmer, if not released, it will be released automatically after the program ends
The global area and the code area exist before the program runs, and the stack area and heap area only exist after the program runs.
Code area
- Store the machine instructions executed by the CPU
- The code area is shared. The purpose of sharing is to have a copy of the code in the memory for frequently executed programs.
- The code area is read-only , the reason for making it read-only is to prevent the program from accidentally modifying its instructions
Global area
- Global variables and static variables are stored here.
- The global area also contains the constant area, and string constants and other constants are also stored here.
- The data in this area is released by the operating system after the program ends.
Stack area
- Automatically allocated and released by the compiler, storing function parameter values, local variables, etc.
- Note : Do not return the address of the local variable, the data opened in the stack area is automatically released by the compiler
Heap area
- The heap area data is opened and released by the programmer
- Heap data uses
new
keywords to open up memory
Case
#include <iostream>
using namespace std;
int main(int argc, char* agrv[])
{
// 利用new关键在在堆区开辟一块内存,new 返回是指定类型的指针
int* a = new int(10);
printf("%d\n",*a);
printf("%d\n", *a);
printf("%d\n", *a);
// 使用delete关键字释放
delete a;
// 将a指向null
a = NULL;
printf("%d\n",a);
return 0;
}
Use new to create data
#include <iostream>
using namespace std;
int main(int argc, char* agrv[])
{
// 中括号代表在堆内存中新建数组
int* p = new int[10];
int i;
for (i = 0; i < 10; i++)
{
p[i] = i + 100;
}
for (i = 0; i < 10; i++)
{
printf("%d\n",*p);
p++;
}
return 0;
}
The delete keyword releases memory
Release variable
delete 变量名;
Free array
delete[] 数组名;