Wiki
Memory Partitioning and Lifecycle
1.Program execution order and variable lifecycle
1.1.Code execution approach
Starting from the main function, the code runs line by line. (A project has one and only one main function.)

1.2.Lifecycle
-
Local variables:
-
Location: Variables declared inside a function or block are called local variables.
-
Scope: They can only be used by statements inside that function or block of code. Local variables are not known outside the function.
-
#include <stdio.h>
int add(int a,int b);
int main ()
{
/* 局部变量声明 */
int a, b;
int c;
/* 实际初始化 */
a = 10;
b = 20;
c = add(a,b);
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
int add(int x,int y)
{
int z = x + y;
return z;
}
Operation result:
value of a = 10, b = 20 and c = 30
-
Global variables
-
Position: Global variables are defined outside of functions, usually at the top of the program.
-
Scope: Global variables are valid throughout the entire program lifecycle and can be accessed inside any function.
-
#include <stdio.h>
/* 全局变量声明 */
int g;
int main ()
{
/* 局部变量声明 */
int a;
/* 静态(全局)变量声明 */
static int b;
/* 实际初始化 */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
Operation result:
value of a = 10, b = 20 and g = 30
In a program, local variables and global variables can have the same name, but within a function, if two names are the same, the local variable value will be used, and the global variable will not be used.
#include <stdio.h>
void tset();
/* 全局变量声明 */
int g = 20;
int main ()
{
/* 局部变量声明 */
int g = 10;
printf ("value of g = %d\n", g);
test();
return 0;
}
void test()
{
printf("value of g = %d\n",g);
}
Run result: Compilation failed: the function definition name is tset, but main is called in test(); the compiler reports that test is undeclared.
1.3.Memory Four Regions
This content cannot be displayed outside of Feishu Docs at this time
-
Static storage area (global area) : It can be divided into the rodata area, the data area, and the bss area. Initialized read-only constants are placed in rodata, and initialized non-zero variables are placed in the data area; variables that are not initialized or whose value is zero are placed in the bss area and are usually initialized by default to 0 (for numeric data types), '\0' (char type), and NULL (pointer type).
-
Stack area (stack) : Local variables are stored in this area. If local variables are not initialized, then the local variables contain random values. The capacity is very small.
-
Heap area (heap) : Memory space is allocated to variables by the programmer and is allocated and freed by the programmer. If the programmer does not free the memory, a memory leak will occur. When the program ends, the system will help free memory that has not been freed.
-
Code area : Stores the machine instructions executed by the CPU and is usually read-only.
2.Memory Partitioning Model
C++When a program is executing, memory is broadly divided into4 regions
- Code segment: stores the binary code of the function body, managed by the operating system
- Global segment: stores global variables, static variables, and constants
- Stack segment: automatically allocated and released by the compiler, stores function parameter values, local variables, etc.
- Heap segment: allocated and released by the programmer; if the programmer does not release it, the operating system reclaims it when the program ends
Significance of the four memory regions:
Data stored in different regions is given different lifecycles, providing us with greater programming flexibility.
2.1.Before program execution
After the program is compiled, an exe executable is generated,Before the program is executedIt is divided into two areas
Code area:
Stores machine instructions executed by the CPU
The code region issharedThe purpose of sharing is that for frequently executed programs, only one copy of the code needs to exist in memory.
The code area isread-only; the reason for making it read-only is to prevent the program from accidentally modifying its instructions.
Global region:
Global variables and static variables are stored here.
The global area also includes the constant area, where string constants and other constants are also stored.
==The data in this region is released by the operating system after the program ends==.
Example:
//全局变量
int g_a = 10;
int g_b = 10;
//全局常量
const int c_g_a = 10;
const int c_g_b = 10;
int main() {
//局部变量
int a = 10;
int b = 10;
//打印地址
cout << "局部变量a地址为: " << &a << endl;
cout << "局部变量b地址为: " << &b << endl;
cout << "全局变量g_a地址为: " << &g_a << endl;
cout << "全局变量g_b地址为: " << &g_b << endl;
//静态变量
static int s_a = 10;
static int s_b = 10;
cout << "静态变量s_a地址为: " << &s_a << endl;
cout << "静态变量s_b地址为: " << &s_b << endl;
cout << "字符串常量地址为: " << static_cast<const void*>("hello world") << endl;
cout << "字符串常量地址为: " << static_cast<const void*>("hello world1") << endl;
cout << "全局常量c_g_a地址为: " << &c_g_a << endl;
cout << "全局常量c_g_b地址为: " << &c_g_b << endl;
const int c_l_a = 10;
const int c_l_b = 10;
cout << "局部常量c_l_a地址为: " << &c_l_a << endl;
cout << "局部常量c_l_b地址为: " << &c_l_b << endl;
return 0;
}
Execution Results : See the printed result figure below; the address values may differ on each run, so focus on the relative differences among the regions where local variables, global variables, static variables, and constants reside.
Print result:

Summary:
- C++ During program execution, memory is divided into the global area and the code area before the program runs.
- The code area is characterized by being shared and read-only.
- The global area stores global variables, static variables, and constants.
- The constant area stores global constants modified by const and string constants.
2.2.After the program runs
Stack area:
Automatically allocated and released by the compiler, storing function parameter values, local variables, etc.
Note: Do not return the address of a local variable; data allocated in the stack area is automatically released by the compiler.
Example:
int * func()
{
int a = 10;
return &a;
}
int main() {
// 程序从 main 函数开始执行,下面的语句会按顺序运行。
int *p = func();
cout << *p << endl;
cout << *p << endl;
// 返回 0 表示程序正常结束。
return 0;
}
Run result: The program triggered undefined behavior; this run received SIGSEGV and then terminated abnormally, with no reliable normal output.
Heap area:
Allocated and freed by the programmer; if the programmer does not free it, the operating system reclaims it when the program terminates.
In C++, new is mainly used to allocate memory in the heap area.
Example:
int* func()
{
int* a = new int(10);
return a;
}
int main() {
// 程序从 main 函数开始执行,下面的语句会按顺序运行。
int *p = func();
cout << *p << endl;
cout << *p << endl;
// 返回 0 表示程序正常结束。
return 0;
}
Operation result:
10
10
Summary:
Heap data is allocated and freed under programmer management
Heap data uses the new keyword to allocate memory
2.3.new operator
C++ uses the ==new== operator to allocate data on the heap
Data allocated on the heap is manually allocated and manually released by the programmer; release uses the operator ==delete==
Syntax: new 数据类型
Data created using new returns a pointer to the corresponding type of that data.
Example 1: Basic syntax
int* func()
{
int* a = new int(10);
return a;
}
int main() {
int *p = func();
cout << *p << endl;
cout << *p << endl;
//利用delete释放堆区数据
delete p;
//cout << *p << endl; //报错,释放的空间不可访问
return 0;
}
Operation result:
10
10
Example 2: Creating an array
//堆区开辟数组
int main() {
int* arr = new int[10];
for (int i = 0; i < 10; i++)
{
arr[i] = i + 100;
}
for (int i = 0; i < 10; i++)
{
cout << arr[i] << endl;
}
//释放数组 delete 后加 []
delete[] arr;
return 0;
}
Operation result:
100
101
102
103
104
105
106
107
108
109