对于那些未来可能有兴趣了解这些内存段的访问者,我在C语言中写了关于5个内存段的要点:
一些提示:
每当C程序执行时,就会在RAM中分配一些内存用于程序执行。这个内存用于存储频繁执行的代码(二进制数据)、程序变量等。下面的内存段讲的是同样的:
通常有三种变量类型:
局部变量(在C语言中也称为自动变量)
全局变量
静态变量
你可以有全局静态变量或局部静态变量,但上面三个是父类型。
5 C中的内存段:
1. 代码段
The code segment, also referred as the text segment, is the area of memory which contains the frequently executed code.
The code segment is often read-only to avoid risk of getting overridden by programming bugs like buffer-overflow, etc.
The code segment does not contain program variables like local variable (also called as automatic variables in C), global variables, etc.
Based on the C implementation, the code segment can also contain read-only string literals. For example, when you do printf("Hello, world") then string "Hello, world" gets created in the code/text segment. You can verify this using size command in Linux OS.
Further reading
数据段
数据段被分为下面两部分,通常位于堆区域的下面,或者在某些实现中位于堆栈之上,但数据段从不位于堆和堆栈区域之间。
2. 未初始化的数据段
This segment is also known as bss.
This is the portion of memory which contains:
Uninitialized global variables (including pointer variables)
Uninitialized constant global variables.
Uninitialized local static variables.
Any global or static local variable which is not initialized will be stored in the uninitialized data segment
For example: global variable int globalVar; or static local variable static int localStatic; will be stored in the uninitialized data segment.
If you declare a global variable and initialize it as 0 or NULL then still it would go to uninitialized data segment or bss.
Further reading
3.初始化的数据段
This segment stores:
Initialized global variables (including pointer variables)
Initialized constant global variables.
Initialized local static variables.
For example: global variable int globalVar = 1; or static local variable static int localStatic = 1; will be stored in initialized data segment.
This segment can be further classified into initialized read-only area and initialized read-write area. Initialized constant global variables will go in the initialized read-only area while variables whose values can be modified at runtime will go in the initialized read-write area.
The size of this segment is determined by the size of the values in the program's source code, and does not change at run time.
Further reading
4. 堆栈段
堆栈段用于存储在函数内部创建的变量(函数可以是主函数或用户定义的函数),如变量
函数的局部变量(包括指针变量)
传递给函数的参数
返回地址
一旦函数执行完成,存储在堆栈中的变量将被删除。
进一步的阅读
5. 堆段
这个段支持动态内存分配。如果程序员想动态分配一些内存,那么在C语言中可以使用malloc、calloc或realloc方法。
例如,当int* prt = malloc(sizeof(int) * 2)时,将在堆中分配8个字节,并返回该位置的内存地址并存储在ptr变量中。ptr变量将在堆栈或数据段上,这取决于它的声明/使用方式。
进一步的阅读