当前位置:网站首页>Dynamic memory management
Dynamic memory management
2022-07-22 08:41:00 【Populus euphratica under the desert】
Personal home page : Welcome to ——> Populus euphratica under the desert
Ladies and gentlemen , It's beautiful
If you think the article is helpful to you
You can support bloggers with one key and three links
Your every care is the driving force of my persistence
![]()
: This issue focuses on : Knowledge of dynamic memory
I hope everyone can study and work happily every day
Why dynamic memory development ?
What is dynamic memory ?
Dynamic memory is to use malloc,calloc,realloc and free These dynamic memory functions are used to request space from the heap , To the programmer for management and use , This is dynamic memory management .
malloc Use
malloc Is to apply for a space , You need to initialize manually , And manually free And empty
calloc
calloc Is to open up space num individual sizeof( type ) And initialize to 0.
realloc
realloc There are two situations :
1. When the source space is 0, The incoming NULL when , and malloc It works the same .
2. If you expand the space , That is, when the passed in pointer is valid , There are two cases
2.1. If there is enough space behind the original space , Then open up directly behind the original space , Returns the lowest address of the original space .( That is, the return value is the same as the incoming value )
2.2. If there is not enough space behind the original space , Then the function will be on the heap , Find a space that can meet the space size required by users , Then copy the original spatial data to the space opened by the function , Then release the original space , Return the lowest address of the reopened space .
This is generally rare , So no more examples .
C Program address space
First of all, we need to understand that the stacking area is C Where is the program address space ? Or say C What is the program address space ?
Today we mainly talk about the pile area .
Why dynamic memory development ?
First of all, we know that the normal application space can be applied directly on the stack area , So why do we need dynamic memory development ?
for instance :
We need to store some numbers , These numbers can be many , There may be very little , At this time, how can we apply for space in the stack area ?
In the idea of saving everything , We need to open up more space , But the stack space is limited , A little bigger will cause stack overflow , That's why there's a heap area .
Error accessing memory
For example, define a structure , Among them, the structure members are dynamically opened up , If not initialized, use , Then it will lead to an error in accessing memory .
struct stu { char* p; int age; }s1; int main() { strcpy(s1.p, " Under Populus euphratica "); s1.age = 18; return 0; }
there s1.p Although it's a variable , But there is no space for relativity , So it will lead to an error in accessing memory .
It says , It should be given to s.p Open up space , Let's see how to open it up , The following development is no problem .
struct stu { char* p; int age; }s1; void Show(char *name) { printf("%s\n", name); } int main() { struct stu s1 = { NULL, 0 }; s1.p = (char *)malloc(sizeof(char)* 30); strcpy(s1.p, " Under Populus euphratica "); Show(s1.p); free(s1.p); s1.p = NULL; return 0; }
Pointer legitimacy problem
First , what " legal " The pointer of ?
Generally speaking , Is that the passed pointer can be used normally .
If a pointer has a point ( The wild pointer also has a point , Just don't know where to point ), Then we can't judge " legal " sex . So we ask that if the pointer is not used directly , Then it should be assigned to NULL, So we can verify ” legal “ When it comes to sex , It becomes to judge whether the pointer is NULL.
After improving the above code, it will become the following code :
struct stu { char* p; int age; }s1; void Show(char *name) { if (name == NULL) { exit(-1); } printf("%s\n", name); } int main() { struct stu s1 = { NULL, 0 }; s1.p = (char *)malloc(sizeof(char)* 30); if (s1.p == NULL) { exit(-1); } strcpy(s1.p, " Under Populus euphratica "); Show(s1.p); free(s1.p); s1.p = NULL; return 0; }
Here we judge whether the pointer is NULL, This avoids null pointers . You can also use assert( macro ) To assert that , Reference header file "assert.h", However, this macro can only be used in the debug version , Cannot be used for release version .
Memory out of bounds
I believe everyone has heard of the topic of memory cross-border , Will the pointer cross the boundary and report an error ?
Sometimes when the pointer is out of bounds, an error will not be reported , such as :
perhaps malloc There was no free There is also a probability of not reporting an error .
But no free More serious things will happen , It's called a memory leak .
Memory leak
Memory leaks are simply , The program only requests memory , No release, No free.
So if there is no program , Or the program exits , So is there a memory leak problem ?
If the program exits , Then the operating system will forcibly reclaim the requested memory .
The biggest fear of memory leakage is some programs that will never quit voluntarily , Then it's a terrible thing , A process , Only apply for memory , Don't release , Then there is no memory available .
free How much space ?
We only know free From , So how big is the release ?
Let's take a look at ,free The size of the is much larger than the free space , So you can say , I malloc It's bigger than we're applying for .
because malloc To apply for space, there should be extra space to manage the applied space , So it's bigger than what we normally apply for , So if we malloc If you want to cross the border, you don't have to report an error .
free What is the release ?
free After that, we usually set the pointer to null , Why? ? Will it still point to the original space if it is not empty ?
We can see that the direction of space has not changed , In other words, the direction has not changed , So what has changed ?
The change is p Relationship with the heap application , therefore free Is to change the relationship ,free The essence is to change the relationship , in other words p It also points to the space applied for in the heap area , So we should break this relationship , Just put p Set as NULL.
It's like talking about your girlfriend , It's all broken up , You shouldn't leave your contact information , So it's time to break the contact information .
Next up :
In the next issue, we'll talk about functions
The next issue is more exciting ~!~!~!
边栏推荐
- p[0]作为for循环的判断条件
- STM32 HAL库 SPI总是读出FF的问题解决!
- Shell练习:统计词频
- 9月备忘录
- Self study golang [Chapter 3: the first go language program] use GoLand to create the first go program, the main function and init function, and use go to run Windows commands and realize the data out
- verilog——74HC85四位数值比较器并扩展为16位数值比较器
- Why not overwrite when pasting in excel
- STM32 SPI reading data is inaccurate, only the first time is correct, and the latter is not correct
- Self study golang [3.8 use go language to find the longest substring without repeated characters] exercise code
- How to open stdio in C h ? How to find the definition of printf?
猜你喜欢
Location Cache 模块浅析及 OCP 监控、报警详解
VS2022无法使用scanf的解决办法,‘scanf‘: This function or variable may be unsafe. Consider using scanf_s instea
【flex布局快速上手】快速理解flex布局用法,通过常见的四个布局案例解释【详细注释,一看就会】
电商大促就靠RPA,摆脱重复劳动,急速提效
七/四/五层网络模型
不断提升认知,从而达到交易的最高级别——稳定盈利(终)
In Excel, the shortcut key of "insert cut cell"
Self study golang [3.1 defining variables] use VaR keyword to define variables, use var() to define variables collectively, omit int keyword and VaR keyword, and use colon: to replace the definition
Analysis of location cache module and detailed explanation of OCP monitoring and alarm
FFmpeg 音频解码(秒懂)
随机推荐
自学golang【3.6切片slice的练习代码】切片的长度,上限,复制,删除与增加
STM32 HAL库 SPI总是读出FF的问题解决!
Quantitative transaction journal - fallback analysis - February 6, 2021
Implementation of hardware watchdog
Verilog -- 74hc194 multifunctional bidirectional shift register
Percona xtradb cluster installation
十年交易员重磅推荐:简单易操作的突破回调策略
【踩坑】npm安装报错解决办法
C语言刷题笔记之基础不牢地动山摇 <一>
软考中级【数据库系统工程师】第2章:程序语言基础知识,自学软考笔记,程序语言概述程序语言翻译基础低级语言和高级语言编译和解释的区别中缀、前缀与后缀表达式程序语言的数据成分1)常量和变量2)全局变量和局
Soft test intermediate [Database System Engineer] Chapter 0: how to prepare for the test by self-study, test introduction, test preparation materials, size score distribution in the morning and aftern
量化交易日记-回撤分析-2021年02月6日
自学golang【3.7map的练习代码】
Pytorch学习(一).深度学习回顾和Pytorch简介
Can you do application development without programming? Yes!
MySQL binlog
Self study golang [3.3go language loop statement] for loop syntax structure, omit initial conditions, omit incremental conditions, omit the application of end conditions
Verilog -- 74hc85 four bit numeric comparator and extended to 16 bit numeric comparator
Verilog——串行四位加法器和超前四位加法器74HC283
Shell exercise: Statistics of word frequency