当前位置:网站首页>Memory allocation - static storage stack heap and static variable
Memory allocation - static storage stack heap and static variable
2022-06-29 10:53:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
One 、 The basic composition of memory
Programmable memory is basically divided into several parts : Static storage area 、 Stack area and stack area . They have different functions , They are used in different ways . Static storage area : Memory is allocated when the program is compiled , The whole running period of the program in this area exists . It mainly stores static data 、 Global data and constants . The stack area : When executing a function , The memory units of local variables in the function can be created on the stack , At the end of the function, these storage units are automatically released . Stack memory allocation operations are built into the processor's instruction set , It's very efficient , But the allocated memory capacity is limited . Heap area : Also called dynamic memory allocation . When the program is running malloc or new Apply any size of memory , It is the programmer's responsibility to use... When appropriate free or delete Free memory . The lifetime of dynamic memory can be determined by us , If we don't free memory , The program will release dynamic memory only at the end . however , Good programming habits are : If a dynamic memory is no longer used , It needs to be released , otherwise , We think there is a memory leak .
Code section : Store the binary code of the function body .
Text constant area — That's where constant strings are put . Released by the system at the end of the program .
Function pointer to Code District , It is the instruction code for program operation , Data pointer to Data,Heap,Stack District , It is all kinds of data that the program depends on to run
Declare in the file scope inline The function defaults to static Storage type ,const Constant defaults to static Storage , If you add extern, External storage type .
Two . Global static variables
1. Add keywords before global variables static, Global variable is defined as a global static variable .
1) Location in memory : Static storage area ( The static storage area exists throughout the program )
2) initialization : Uninitialized global static variables are automatically initialized to 0( The value of the automatic object is Any of the , Unless it's shown )
3) Scope : Global static variables are not visible outside of the declared file . Exactly from the beginning of the definition to the end of the file .
The benefits of defining global static variables :
<1> Will not be accessed by other files , modify
<2> Variables with the same name can be used in other files , There will be no conflict .
2. Local static variable
Add the keyword before the local variable static, A local variable is defined as a local static variable .
1) Location in memory : Static storage area
2) initialization : Uninitialized local static variables are automatically initialized to by the program 0( The value of the automatic object is arbitrary , Unless it's shown )
3) Scope : Scope is still local , When the function or block that defines it ends , The scope then ends .
notes : When static It's used to modify local variables , It changes the location of local variables , From the original stack storage to static storage . But after a local static variable leaves the scope , Not destroyed , It's still in memory , Until the end of the program , It's just that we can't visit him anymore .
When static When it comes to modifying global variables , It changes the scope of global variables ( It's invisible outside the document that declared him ), But it didn't change its storage location , Still in static storage .、
3、 ... and 、 The difference between the three Let's use the code snippet to see what operations and differences are required for such three parts of memory , And what should be paid attention to . Patients with a : Static storage area and stack area char* p = “Hello World1”; char a[] = “Hello World2”; p[2] = ‘A’; a[2] = ‘A’; char* p1 = “Hello World1;”
This program has errors , The error occurs when p[2] = ‘A’ At this line of code , Why? , It's a variable. p And variable arrays a All exist in the stack area ( Any temporary variable is in the stack , Included in main() Variables defined in functions ). however , data “Hello World1” And data “Hello World2” Is stored in different areas . Because of the data “Hello World2” Exists in the array , therefore , This data is stored in the stack area , There is no problem modifying it . Because pointer variables p An address that can only store a certain storage space , data “Hello World1” Is a string constant , So it is stored in the static storage area . Though through p[2] You can access the third data unit in the static storage area , That is, the characters ‘l’ The storage unit where the . But because of the data “Hello World1” Is a string constant , Can't change , So when the program is running , Memory errors are reported . also , If at this time p and p1 When output, you will find p and p1 The address stored inside is exactly the same . let me put it another way , Keep only one copy of the same data in the data area
Example 2 : Stack area and heap area char* f1() { char* p = NULL; char a; p = &a; return p; } char* f2() { char* p = NULL: p =(char*) new char[4]; return p; }
Both of these functions return the address of a storage space , What's the difference between them ?f1() Function returns a storage space , But this space is temporary . in other words , This space has only a short life cycle , Its life cycle is in the function f1() At the end of the call , It will lose its life value , namely : This space is freed . therefore , When calling f1() Function time , If the program has the following statement : char* p ; p = f1(); *p = ‘a’;
here , Compilation does not report errors , But when the program is running , An unexpected error will occur . because , You should not operate on memory ( namely , The storage space that has been released ) It's operated . however , by comparison ,f2() There is no problem with the function . because ,new This command requests storage space in the heap , Once the application is successful , Unless you put it delete Or the program ends , This memory will always exist . Or another way to think about it , Heap memory is a shared unit , Can be accessed by multiple functions . If you need to have more than one data to return but have no way , Heap memory would be a good choice . But be sure to avoid the following : void f() { … char * p; p = (char*)new char[100]; … }
This program does a very meaningless and harmful thing . because , Although heap memory is requested ,p Save the first address of heap memory . however , This variable is temporary , When the function call ends p The variable disappears . in other words , There are no variables to store the first address of this heap memory , We will never be able to use that heap memory again . however , This heap of memory is always marked as being used by you ( Because it is not the end of the program , You didn't put it delete, So this heap memory has been identified as the current owner of your program ), Then other processes or programs cannot be used . We call this immoral “ Hooliganism ”( We don't have to , But not to be used by others ) It's called a memory leak . This is us. C++ Programmers' taboos !! Please be sure to avoid this happening . All in all , For heap area 、 The biggest difference between stack area and static storage area is , Stack life cycle is very short . But the life cycle of heap and static storage is equivalent to the life of the program ( If you don't put heap memory in the middle of the program delete Words ), We call this variable or data a global variable or data . however , The use of memory space in heap area is more flexible , Because it allows you to... When you don't need it , Release it at any time , The static storage area will always exist in the whole life cycle of the program .
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/132438.html Link to the original text :https://javaforall.cn
边栏推荐
- UserWarning: Usage of dash-separated ‘script-dir‘ will not be supported in future versions. note
- Given the values of two integer variables, the contents of the two values are exchanged (C language)
- Findbugs修改总结
- Luoqingqi: has high-end household appliances become a red sea? Casati took the lead in breaking the game
- USB转RS485串口电路设计「建议收藏」
- BUUCTF--reverse2
- AQS之Atomic详解
- STM32F1与STM32CubeIDE编程实例-超声波测距传感器驱动
- The encryption market has exploded one after another. Can Celsius avoid bankruptcy?
- 免费送书啦!畅销书《 OpenCV图像处理入门与实践》一本全搞定
猜你喜欢

UserWarning: Usage of dash-separated ‘script-dir‘ will not be supported in future versions. note

“AI x 科学计算”进行时,华为昇思 MindSpore 赛题火热开启,等你来!

【FreeRTOS】08 互斥信号量、优先级反转问题

Ikvm Net project progress

Fully understand the volatile keyword

全面理解Synchronized

Analysis of BlockingQueue source code of AQS

在 2022 年找工作,毕业生们的 “最后一课”

AQS之Atomic详解

你的项目需要自动化测试吗?
随机推荐
Does your project need automated testing?
Print leap years between 1000 and 2000 (C language)
二叉树
SQL Server 数据库的几种简单查询
这个mySQL安装的时候怎么搞去了?
The product strength is not inferior to that of BYD. Geely Dihao l Raytheon hi · x delivered 10000 units in the first month
励志!专科“逆袭”读浙大硕士,3篇SCI,最终成清华博士!
嵌入式学习书籍推荐[通俗易懂]
STM32F1与STM32CubeIDE编程实例-超声波测距传感器驱动
LVGL库入门教程 - 动画
Excel date and number format processing
请问,flink sql 批任务,两表或多表join(inner join 或 outer join
任职 22 年,PowerShell 之父将从微软离职:曾因开发 PowerShell 被微软降级过
stream流(Collectors)用法
最后的 48 小时!云 XR 专题赛邀你一起绽放精彩,我们赛场见!
历史上的今天:马斯克出生;微软推出 Office 365;蔡氏电路的发明者出生
有了这款工具,自动化识别验证码再也不是问题
1- database understanding
SQL Server 数据库增删改查语句
Creating postgre enterprise database by ArcGIS