当前位置:网站首页>Four areas of telephone memory
Four areas of telephone memory
2022-06-21 17:25:00 【Soy sauce;】
1. Memory partition
Before you run
We want to execute what we write c Program , Then the first step is to compile the program .
|
When we compile and generate the executable , We passed the linux Next size Command can view the basic information of an executable binary file :

You can see from the picture above , Before running the program , in other words Before the program is loaded into memory , The executable program has been divided internally 3 Segment information , Respectively Code section (text)、 Data area (data) And uninitialized data area (bss)3 Parts of ( Some people put data and bss Together, they are called static areas or global areas ).
1. Code section Deposit CPU Machine instructions executed . Usually, the code area can be share Of ( That is, other executors can call it ), The purpose of making it sharable is for programs that are frequently executed , You only need to have... In memory Just a copy of the code . The code area is usually read-only Of , The reason to make it read-only is to prevent the program from accidentally modifying its reference t Make . in addition , The code area also plans information about local variables . 2. Global initialization data area / Static data area (data paragraph )( static state , overall situation , often ) This section contains the..., which is explicitly initialized in the program Global variables 、 Already initialized Static variables ( Including global static variables and const data ( Like string constants ). 3. Uninitialized data area ( Also called bss District ) The deposit is Global uninitialized variables and uninitialized static variables . The uninitialized data area is initialized by the kernel to 0 Or empty (NULL). |
Generally speaking , After the program source code is compiled, it is mainly divided into two segments : Program instructions ( Code section ) And program data ( Data area ). Code segments belong to program instructions , And data field segments and .bss Segment belongs to program data . |
So why separate program instructions from program data ?
|
After running
Before the program is loaded into memory , Code area and global area (data and bss) The size of is fixed , The program cannot be changed during operation . then , Run executable , The operating system puts the physical hard disk program load( load ) To the memory , In addition to the information from the executable program to separate the code area (text)、 Data area (data) And uninitialized data area (bss) outside , There is also an additional stack area 、 Heap area .
1. Code section (text segment) It loads the executable code snippet , All executable code is loaded into the code area , This memory cannot be modified during operation . 2. Uninitialized data area (BSS) The executable is loaded BSS paragraph , The location can be separated or close to the data segment , Data stored in data segments ( Global not initialized , Static uninitialized data ) The life cycle of the program is the whole running process .
3. Global initialization data area / Static data area (data segment) The executable data segment is loaded , Stored in data segments ( Global initialization , Static initialization data , Literal constants ( read-only )) The life cycle of data is the whole process of program running . 4. The stack area (stack) for example int a=1; Stack is an advanced memory structure , Release is automatically allocated by the compiler , Stores the parameter values of the function 、 Return value 、 Local variables, etc . Loading and releasing in real time during program running , therefore , The lifetime of the local variable is from applying to releasing the stack space . After the function executes, the local variable is released . 5. Heap area (heap) A heap is a big container , Its capacity is much larger than the stack , But there is no stack like the order of first in and last out . For dynamic memory allocation . The heap is in memory BSS Between area and stack area . Usually assigned and released by programmers , If programmers don't release , Recycle by the operating system at the end of the program . |

Related data types and their storage locations :
static and extern Focus on memory
type | Scope | Life cycle | Storage location |
auto Variable | a pair {} Inside | The current function | The stack area |
static local variable | a pair {} Inside | The whole running period of the program | Initialize at data paragraph , Not initialized at BSS paragraph |
extern Variable | Whole procedure | The whole running period of the program | Initialize at data paragraph , Not initialized at BSS paragraph |
static Global variables | Current file | The whole running period of the program | Initialize at data paragraph , Not initialized at BSS paragraph |
extern function | Whole procedure | The whole running period of the program | Code section |
static function | Current file | The whole running period of the program | Code section |
register Variable | a pair {} Inside | The current function | The runtime is stored in CPU register |
String constant | Current file | The whole running period of the program | data paragraph |
2. Partition model
The stack area
The memory is managed by the system . The main storage function parameters and local variables . After the function completes execution , The system releases the memory of stack area by itself , No need for user management .
matters needing attention : Do not return the local variable address , Local variables are released after the function body is executed , Another operation is illegal , The result is unknown .
#char* func(){// Do not return the local variable address , Local variables are released after the function body is executed , Another operation is illegal , The result is unknown . char p[] = "hello world!"; // Store... In the stack area The statement printf("%s\n", p); return p; } void test(){ char* p = NULL; p = func(); printf("%s\n",p); } |
Heap area
Manually requested by the programmer , Hand release , If not released manually , After the program is completed, it is recycled by the system , The life cycle is the entire program run time . Use malloc perhaps new Apply for a heap .
malloc apply free Release Then point the pointer to null , Avoid wild pointer
matters needing attention : Null pointer in the calling function , The called function modifies an unsuccessful with a sibling pointer , There is no change p Of itself , Function will be passed into the newly opened space , To use a higher-level pointer to change its address for decoration .
#define _CRT_SECURE_NO_WARNINGS int * getSpace() if (p == NULL) for (int i = 0; i < 5;i++) } void test01() for (int i = 0; i < 5;i++) // Data created manually in the heap , Remember to release manually }
} void test02() printf("%s\n", p);
void test03() allocateSpace2(&p); printf("%s\n", p); free(p); } int main(){ |


Heap allocated memory API:
#include <stdlib.h> void *calloc(size_t nmemb, size_t size); function : Allocate... In memory dynamic storage nmemb The block length is size A contiguous region of bytes .calloc Automatically allocate the allocated memory Set up 0. Parameters : nmemb: Number of memory units required size: The size of each memory unit ( Company : byte ) Return value : success : The starting address of the allocated space Failure :NULL |
#include <stdlib.h> void *realloc(void *ptr, size_t size); function : Reassign malloc perhaps calloc Function allocates the size of memory space in the heap . realloc It will not automatically clean up the increased memory , It needs to be cleaned by hand , If there is a continuous space after the specified address , Then it will add memory based on the existing address , If there is no space after the specified address , that realloc Will reallocate new contiguous memory , Copy the value of the old memory to the new memory , Free old memory at the same time . Parameters : ptr: For the previous use malloc perhaps calloc Allocated memory address , If this parameter is equal to NULL, So and realloc And malloc Consistent function size: To reallocate the size of memory , Company : byte Return value : success : Newly allocated heap memory address Failure :NULL |
Sample code :
void test01(){ int* p1 = calloc(10,sizeof(int)); if (p1 == NULL){ return; } for (int i = 0; i < 10; i ++){ p1[i] = i + 1; } for (int i = 0; i < 10; i++){ printf("%d ",p1[i]); } printf("\n"); free(p1); } void test02(){ int* p1 = calloc(10, sizeof(int)); if (p1 == NULL){ return; } for (int i = 0; i < 10; i++){ p1[i] = i + 1; } int* p2 = realloc(p1, 15 * sizeof(int)); if (p2 == NULL){ return; } printf("%d\n", p1); printf("%d\n", p2); for (int i = 0; i < 15; i++){ printf("%d ", p2[i]); } printf("\n"); // Reassign for (int i = 0; i < 15; i++){ p2[i] = i + 1; } // Print again for (int i = 0; i < 15; i++){ printf("%d ", p2[i]); } printf("\n"); free(p2); } |
overall situation / Static zone ( Data area )
- The variables in the global static area have allocated memory space and initialized in the compilation stage . The program in this block exists all the time , It mainly stores Global variables 、 Static variables and Constant .
static state :static
matters needing attention :
- Allocate memory before the program runs
- The lifecycle dies before the file runs
- It belongs to internal link property , Use... In the current file ( Normally, it is used in the current file )
Global variables :extern
matters needing attention :
- The default global variable plus extern
- It belongs to external link property , Tell the compiler that other files can be used ( An external command that cannot be resolved , Error in link phase )
Static variables and global variables
#define _CRT_SECURE_NO_WARNINGS //1、 Static variables // characteristic : Initialize only once , Allocate memory at compile time , It belongs to internal link property , Can only be used in the current file void test01() //a and b The life cycle of is the same
extern int g_a = 100; // stay C Under the language Keywords are hidden in front of global variables extern, It belongs to external link property void test02() printf("g_b = %d\n", g_b); } int main(){ system("pause"); |
Constant :
a. const Constant decorated
matters needing attention :
- const Decorated global variables , Assign to constant area ( read-only ) in // direct / Indirect modification Failure
- const Modified local variables // Assign to the stack , Not protected by the constant area ( Also known as pseudo constants )/ Failed to modify directly // Indirect modification success //C Under the language Called pseudo constant
- // Arrays cannot be initialized with pseudo constants
const Constant :
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>//1、const Decorated global variables , Even if the grammar passes , But the runtime is protected by the constant area , Run failed
const int a = 10; // Put it in the constant areavoid test01()
{
//a = 100; // direct / Indirect modification Failureint * p = &a;
*p = 100;printf("%d\n", a);
}
//2、const Modified local variables
void test02()
{
const int b = 10; // Assign to the stack , Not protected by the constant area ( Also known as pseudo constants )
//b = 100; // Failed to modify directly
// Indirect modification success
//C Under the language Called pseudo constant
int * p = &b;
*p = 100;
printf("b = %d\n", b);//int a[b];// Arrays cannot be initialized with pseudo constants
}
Be careful :
(1) There is no distinction between initialized and uninitialized data areas , This is because variables in the static storage area are initialized if they are not displayed , The compiler will automatically initialize in the default way , That is, there are no uninitialized variables in the static storage area . (2) Constants in the global static storage area are divided into constant variables and string constants , Once initialized , Do not modify the . Constant variables in static storage are global variables , Unlike local constants , The difference is that local constants are stored on the stack , Actually, it can be modified indirectly through pointers or references , The global constant is stored in the static constant area and cannot be modified indirectly . (3) String constants are stored globally / Constant area of static storage . |
b. String constant
matters needing attention :
String constants are stored in the constant area , Modifying string constants is not allowed
For different compilers, the optimization of string constants is different
//3. String constant
void test03()
{
char * p1 = "hello world";// All three are in one area
char * p2 = "hello world";
char * p3 = "hello world";printf("%d\n", p1);
printf("%d\n", p2);
printf("%d\n", p3);
printf("%d\n", &"hello world");
p1[0] = 'z'; // Modifying string constants is not allowed
printf("%c\n", p1[0]);}
int main(){
//test01();
//test02();
test03();
system("pause");
return EXIT_SUCCESS;
}
Deepen the understanding :
char* func(){ static char arr[] = "hello world!"; // Store in static area Can read but write arr[2] = 'c'; char* p = "hello world!"; // overall situation / Static zone - String constant area //p[2] = 'c'; // read-only , Do not modify the printf("%d\n",arr); printf("%d\n",p); printf("%s\n", arr); return arr; } void test(){ char* p = func(); printf("%s\n",p); } |
String constant Modifiable or not ? String constant optimization :
ANSI C Specified in the : Modify string constants , The result is undefined .
ANSI C There is no provision for compiler implementers to handle strings , for example :
1. Some compilers can modify string constants , Some compilers cannot modify string constants .
2. Some compilers treat multiple identical string constants as one ( This optimization can occur in string constants , Save a space ), Some do not do this optimization . If optimized , This may lead to the modification of one string constant and the change of other string constants , The result is unknown .
So try not to modify string constants !
C99 standard :
char *p = "abc"; defines p with type ‘‘pointer to char’’ and initializes it to point to an object with type ‘‘array of char’’ with length 4 whose elements are initialized with a character string literal. If an attempt is made to use p to modify the contents of the array, the behavior is undefined.
Whether the string constant addresses are the same ?
tc2.0, Same as the document Different string constant addresses .
Vs2013, The string constant address is the same for the same file and different files .
Dev c++、QT Same as file , Different files are different .
3. summary
Understanding C/C++ Memory partition error , The following terms are often encountered : Data area , Pile up , Stack , Static zone , The constant area , Global area , String constant area , Text constant area , Code area, etc , Beginners are confused . ad locum , Try to clarify the relationship between the above partitions .
The data area includes : Pile up , Stack , overall situation / Static storage area .
overall situation / Static storage includes : The constant area , Global area 、 Static zone .
The constant area includes : String constant area 、 Constant variable area .
Code section : Store the compiled binary code of the program , Non addressable area .
so to speak ,C/C++ There are only two memory partitions , Code area and data area .
边栏推荐
- 模板:P6114 【模板】Lyndon 分解&Runs(字符串)
- 从北京“润”到芝加哥,工程师宝玉“滋润”成长的秘诀
- 海外new things | 美国人工智能初创「Zoovu」新一轮融资1.69亿美元,为消费者优化线上的“产品发现”体验
- Yaml data driven demo
- 南京大学 静态软件分析(static program analyzes)-- introduction 学习笔记
- Hairui technology completed the pre-A round of financing of tens of millions of yuan to build the first artificial intelligent distribution Internet of things in China
- 今年的 618 不行了?
- [Error] ‘vector‘ was not declared in this scope
- Ares Ares I pledged LP mining crowdfunding model DAPP smart contract customization
- qtcreator报错解决
猜你喜欢
随机推荐
Can Koufu open a futures account? Is it safe?
Generating test reports using the unittest framework
如何判断DNS解析故障?如何解决DNS解析错误?
模板:P6114 【模板】Lyndon 分解&Runs(字符串)
How to open an account for futures agricultural products? How much is the handling charge?
容器云是什么意思?与堡垒机有什么区别?
Vector data download for mainland and global epidemic data, based on geo JSON to SHP
Pytest框架实现前后置的处理
Pytest框架
碳排放的计算
qtcreator報錯解决
Hairui technology completed the pre-A round of financing of tens of millions of yuan to build the first artificial intelligent distribution Internet of things in China
使用 Guzzle 中间件进行优雅的请求重试
阿里云服务器+宝塔面板+无域名部署web项目
[learn FPGA programming from scratch -38]: Advanced - syntax - functions and tasks
【mysql学习笔记14】DQL语句执行顺序
Yaml data driven demo
Unittest框架
Qt5 knowledge: string list qstringlistmodel
Test log of unittest framework









