当前位置:网站首页>Memory management of C language - heap, stack, etc
Memory management of C language - heap, stack, etc
2022-07-19 00:04:00 【Let it be~】
We need to know —— Variable , In fact, it's just a name of memory address . In statically compiled programs , All variable names are converted to memory addresses at compile time . The machine doesn't know our name , Just the address .
The use of memory is one of the important factors in programming , This is not only because the system memory is limited ( Especially in embedded systems ), And memory allocation will directly affect the efficiency of the program . therefore , We need to C Memory management in language , Have a systematic understanding of .
stay C In language , Defined 4 Two memory intervals : Code section ; Global variables and static variables area ; Local variable area is stack area ; Dynamic storage , That is, pile area ; As follows :
1> The stack area (stack)— Release is automatically allocated by the compiler , Stores the parameter values of the function , The value of a local variable etc. . It operates like a stack in a data structure .
2> Heap area (heap) — Release is usually assigned by the programmer , If programmers don't release , At the end of the program, the OS Recycling . Notice that it's not the same as the heap in the data structure , The distribution method is similar to the linked list .
3> Global area ( Static zone )(static)— Global and static variables The storage of is put together , Initialized global and static variables in one area , Uninitialized global variables and uninitialized static variables are in adjacent Another area .- Released by the system at the end of the program .
4> The constant area — That's where constant strings are put . Released by the system at the end of the program .
5> Program code area — Store the binary code of the function body .
Let's take a look at this picture :

chart 1
First we need to know , Source code compiled into programs , The program is on the hard disk , Not in memory ! Only when it is executed will it be called into memory ! Let's look at the program structure ,ELF Yes Linux The main executable file format of .ELF File by 4 Part of it is made up of , Namely ELF head (ELF header)、 Program header (Program header table)、 section (Section) And the nodal table (Section header table). As follows :
1>Program header Describes the location of a segment in a file 、 Size, and the location and size of it when it is put into memory . The information to be loaded ;
2>Sections preserved object File information , From a connection point of view : Include instructions , data , The symbol table , Relocation information and so on . In the picture , We can see Sections It includes :
text Text knot Store instructions ;
rodata Data junction readonly;
data Data junction Can read but write ;
3>Section Head table (section header table) Contains a description file sections Information about . Every section There is an entry in this table ; Each entry gives the section Name , size , Information, etc. . amount to Indexes !
And the program is loaded into memory , How is it distributed ? Let's take a look at the picture above :
Text and initialized data and uninitialized data are what we call data segments , The body is the code snippet ;
2> Above the text section is the constant area , Above the constant area are global variables and static variables , What they occupy are the initialized data and the uninitialized data ;
3> On top of that is the pile , Dynamic storage , Here's up growth ;
4> Above the pile is the stack , It stores local variables , After the execution of the code block where the local variable is located , This memory will be released , Here the stack area is down growth ;
5> The command line argument is 001 And so on. , We've talked about environment variables in previous articles , Those who are interested can go and have a look .
We know , Memory is divided into dynamic memory and static memory , Let's start with static memory .
Static memory
The storage model determines the memory allocation and access characteristics of a variable , stay C There are three main dimensions in language : Storage period 、 Scope 、 link .
1、 Storage period
Storage period : Variable retention time in memory ( Life cycle )
There are two types of storage periods , The key is to see if the variables will be automatically recycled by the system during the execution of the program .
1) Static storage period Static
In the process of program execution, once allocated, it will not be automatically recycled .
- Generally speaking , Any variable that is not defined within a function level code block .
- Whether or not in a code block , Just use static Keyword modifies the variable .
2) Automatic storage period Automatic
All variables except static storage are stored automatically , Or as long as it's defined in a code block static The variable of , The system will automatically allocate and release memory ;
2、 Scope
Scope : Visibility of a variable in its own file that defines the variable ( Access or reference )
stay C In language , Altogether 3 Middle scope :
1) Code block scope
Variables defined in a code block have the scope of the code . From where this variable is defined , By the end of this code block , The variable is visible ;
2) Function prototype scope
Variables that appear in function prototypes , All have function prototype scope , The function prototype scope runs from the variable definition to the end of the prototype declaration .
3) File scope
A variable defined outside of all functions has a file scope , A variable with a file scope is visible from its definition to the end of the file containing the definition ;
3、 link
link : The visibility of a variable in all the files that make up the program ( Access or reference );
C There are three different kinds of links in the language :
1) External links
If a variable can be accessed anywhere in all the files that make up a program , The variable supports external links ;
2) internal link
If a variable can only be accessed anywhere in the file that defines itself , The variable supports internal links .
3) Empty link
If a variable is only private by the current block of code that defines itself , Cannot be accessed by other parts of the program , The variable supports empty links
Let's take a look at a code example :
#include <stdio.h>
int a = 0;// Global initialization area
char *p1; // Global uninitialized area
int main()
{
int b; //b In the stack area
char s[] = "abc"; // Stack
char *p2; //p2 In the stack area
char *p3 = "123456"; //123456\0 In the constant area ,p3 On the stack .
static int c =0;// overall situation ( static state ) Initialization area
p1 = (char *)malloc(10);
p2 = (char *)malloc(20); // Well distributed 10 and 20 The byte area is in the heap area .
strcpy(p1, "123456"); //123456\0 Put it in the constant area , The compiler may match it with p3 The point is "123456" Optimize into a place .
}1.2 Dynamic memory
When the program runs to a variable that needs to be dynamically allocated , You must apply to the system to get a piece of storage space of the required size in the heap , Used to store the variable . When not using the variable , At the end of its life , To display the storage space it takes to free it , So that the system can do the same for the space Make redistribution , Reuse wired resources . The following describes the functions of dynamic memory application and release .
1.2.1 malloc function
malloc The function prototype :

size Is the number of bytes of memory that need to be dynamically applied . If the application is successful , Function returns the starting address of the memory requested , If the application fails , return NULL. Let's look at the following example :

When using this function , The following points should be noted :
1) Only care about the size of the application memory ;
2) The application is a continuous memory . Remember to write wrong judgment ;
3) Display initialization . That is, we don't know what's in this memory , We need to clear it ;
1.2.2 free function
The amount of memory allocated on the heap , Need to use free Function shows release , The function prototype is as follows :

Use free(), There are also the following points to pay attention to :
1) The starting address of the memory must be provided ;
When the function is called , The starting address of the memory must be provided , Cannot provide partial address , It is not allowed to free part of memory .
2)malloc and free Pairs using ;
The compiler is not responsible for dynamic memory release , Need programmer to show release . therefore ,malloc And free It's paired , Avoid memory leaks .

p = NULL Is a must , Because although this memory is released , however p Still pointing to this memory , Avoid next time to p Misoperation of ;
3) Repeated releases are not allowed
Because after this memory is released , It may have been allocated separately , This area is occupied by someone else , If released again , Can cause data loss ;
1.2.3 Other correlation functions
calloc Function to allocate memory needs to consider the type of storage location .
realloc Function to adjust the size of a dynamically allocated memory
1.3 Heap versus stack
1) Application method
stack: Automatically assigned by the system . for example , Declare a local variable in a function int b; The system automatically adds b Open up space
heap: The programmer needs to apply for it himself , And indicate the size , stay c in malloc function , Such as p1 = (char *)malloc(10);
2) System response after application
Stack : As long as the remaining space of the stack is larger than the requested space , The system will provide memory for the program , Otherwise, an exception will be reported indicating that the stack overflows .
Pile up : First of all, you should know that the operating system has a list of free memory addresses , When the system receives an application for a program , Will traverse the list , Find the first heap node whose space is larger than the applied space , Then delete the node from the free node list , And allocate the space of the node to the program , in addition , For most systems , The size of this allocation will be recorded at the first address in this memory space , such , In code delete Statement can correctly release the memory space . in addition , Because the size of the heap node found is not necessarily exactly the size of the request , The system will automatically put the extra part back into the free list .
3) Request size limit
Stack : Stacks are data structures that extend to low addresses , It's a continuous area of memory . The address at the top of the stack and the maximum capacity of the stack are predetermined by the system , The size of the stack is 2M( Some say it is 1M, All in all, it's a constant determined at compile time ), If the requested space exceeds the remaining space of the stack , Will prompt overflow. therefore , The space available from the stack is small .
Pile up : Heap is a data structure extended to high address , It's a discontinuous memory area . This is because the system uses linked list to store the free memory address , Nature is not continuous , The traversal direction of the list is from low address to high address . The size of the heap is limited by the virtual memory available in the computer system . thus it can be seen , The heap gets more flexible space , It's bigger .
4) Comparison of application efficiency
Stacks are allocated automatically by the system , Faster . But programmers can't control it .
The heap is made up of new Allocated memory , Generally speaking, it's slow , And it's prone to memory fragmentation , But it's the most convenient .
5) Heap and stack storage
Stack : On function call , The first one on the stack is the next instruction in the main function ( The next executable statement of a function call statement ) The address of , And then the parameters of the function , In most of C In the compiler , Parameters are pushed from right to left , And then the local variables in the function . Note that static variables are not pushed . When this function call ends , Local variables first out of stack , And then the parameters , Finally, the top of the stack pointer points to the address of the first storage , That is, the next instruction in the main function , The program continues to run from this point .
Pile up : Generally, a byte is used to store the size of the heap in the head of the heap . The specific contents of the heap are arranged by the programmer .
6) Access efficiency comparison
char s1[] = "aaaaaaaaaaaaaaa";
char *s2 = "bbbbbbbbbbbbbbbbb";
aaaaaaaaaaa It's assigned at runtime ;
and bbbbbbbbbbb It's determined at compile time ;
however , In later access , The array on the stack is more than the string the pointer points to ( For example, pile ) fast .
such as :

The corresponding assembly code

The first is to read the elements in the string directly to the register when reading cl in , And the second is to read the pointer value to edx in , According to edx Read character , Obviously slow .
7) The final summary
The difference between heap and stack can be seen in the following metaphor :
It's like eating in a restaurant , Just order ( Issue an application )、 pay 、 And eating ( Use ), When you are full, go , Don't pay attention to cutting vegetables 、 Prepare for dishes and dishes 、 Brush the pot and finish the work , His advantage is fast , But the freedom is small .
It's like making your own favorite dishes , More trouble , But more in line with their own taste , And there's a lot of freedom .
Reference resources : Daniel Tan C The advanced use of language
边栏推荐
- C语言的内存管理-堆、栈等
- Canadian deployer Canadian adapter image construction, deployment
- 一组简单多用途表单小部件代码
- A set of simple multipurpose form widget code
- Pytest interface automated testing framework | introduction to pytest
- 15. Sum of three numbers [list < list < integer> > ans, ans.add (arrays.aslist (num[i], num[j], num[k]))]
- shell第三天小练习 通过自搭建dns服务器访问自搭建nextcloud网盘服务
- Redis has three modes -- master-slave replication, sentinel mode, and cluster
- Responsive form style transparent design
- 推荐一个讲即时通信的博客
猜你喜欢
随机推荐
负责任的AI | 三证加持,澳鹏中国又获ISO9001及27701认证
Jedi survive eating chicken 98K does not automatically close the mirror
学习要有激情
ans1编码解析
Pytest interface automation test framework | secondary encapsulation of requests
matplotlib.pyplot使用(subplots,gray
System.getProperty
Openpose: estimation de la pose 2D Multi - personnes en temps réel à l'aide d'un champ d'affinité partiel
CodeTON Round 1 (Div. 1 + Div. 2, Rated, Prizes)(A-C)
UMAP介绍和代码实例
毕业四年换了3份软件测试工作,我为何依然焦虑?
libtorch cmake
Canvas countless triangle animation JS special effects
Vs publish websites using webdeploy
bufferbloat 与通货膨胀
Iptables learning notes
E. Split Into Two Sets
Glide 源码分析(4.13.2)
关于进程栈空间的实验
go语言实现登录注册收藏相关工具和教程链接








