Memory Partitioning and Lifecycle
Program Execution Order and Variable Lifecycle
Code execution logic
Starting from the main function, the code runs line by line. (There is one and only one main function in a project.)

lifecycle
- Local variables:
- Location: Variables declared inside a function or block are called local variables.
- Scope: They can only be used by statements within that function or code block. Local variables are unknown 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;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
- Global variable
- Location: Global variables are defined outside of functions, typically at the top of the program.
- Scope: Global variables are valid throughout the entire program lifecycle and can be accessed from within 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;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
In a program, local and global variables can have the same name. However, inside a function, if both names are identical, the local variable's value is used, and the global variable is not accessed.
#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);
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
Memory Four Regions
Unable to display this content outside of Feishu documents for now.
- Static Storage Area (Global Area): It can be divided into the rodata section, data section, and bss section. Initialized read-only constants are placed in the rodata section, while initialized non-zero variables are placed in the data section. Variables that are uninitialized or have a value of zero are placed in the bss section, typically defaulting to 0 (for numeric data types), '\0' (for char type), and NULL (for pointer types).
- Stack area: Local variables are stored in this area. If a local variable is not initialized, it will contain a random value. The capacity is very small.
- Heap: Memory space allocated for variables by the programmer, who is responsible for both allocation and deallocation. If the programmer does not free the memory, a memory leak occurs. When the program ends, the system will help release any memory that was not freed.
- Code area: stores machine instructions executed by the CPU, typically read-only.
Memory Partitioning Model
When a C++ program executes, the memory is broadly divided into 4 main areas: the stack, the heap, global/static memory, and the constant area.
- Code Segment: Stores the binary code of function bodies and is managed by the operating system.
- Global area: Stores global variables, static variables, and constants.
- Stack: Automatically allocated and released by the compiler, stores function parameters, local variables, etc.
- The heap: allocated and released by the programmer; if not released by the programmer, it is reclaimed by the operating system when the program terminates.
Significance of the Four Memory Regions:
Assigning different lifecycles to data stored in different memory regions provides us with greater programming flexibility.
Before program execution
After program compilation generates an executable, before its execution, it consists of two distinct regions.
Code section:
stores the machine instructions executed by the CPU
The code section is shared; the purpose of sharing is that for frequently executed programs, only one copy of the code needs to exist in memory.
The code area is read-only, and the reason it is made read-only is to prevent programs from accidentally modifying its instructions.
Global Section:
Global and static variables are stored here.
The global area also contains the constant area, where string constants and other constants are 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;
}
运行结果:见下方打印结果图;地址值每次运行可能不同,重点观察局部变量、全局变量、静态变量和常量所在区域的相对差异。
Print result:

Summary:
- In C++, before program execution, memory is divided into the global area and the code area.
- The code section is characterized as shared and read-only.
- The global area stores global variables, static variables, and constants.
- The constant region stores const-qualified global constants and string constants.
After the program runs
Stack Area:
Automatically allocated and freed by the compiler, it stores function parameters, local variables, and similar data.
Note: Do not return the address of local variables; data allocated on the stack 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;
}
Running/Observing the results: After running, the example will print variable values or addresses; address values depend on the runtime environment, so focus on observing the relative positioning and pointer changes of similar objects.
Heap:
Memory is allocated and freed by the programmer. If the programmer fails to release it, the operating system reclaims it when the program terminates.
In C++, memory is primarily allocated on the heap area using the new operator.
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;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
Summary:
Heap data is managed by the programmer for allocation and release.
Heap area data uses the new keyword to allocate memory.
new operator
In C++, the ==new== operator is used to allocate data on the heap.
Data allocated in the heap is manually allocated and released by the programmer, using the operator ==delete== for deallocation.
Syntax: new 数据类型
Data created with 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;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.
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;
}
Running/Observation Results: After running, the corresponding content will be printed according to the output statements. The variable values can be inferred based on the order of initialization, assignment, and function calls.