当前位置:网站首页>Advanced part 5 of C language. Dynamic memory management
Advanced part 5 of C language. Dynamic memory management
2022-07-24 07:33:00 【And move forward with the high wind - & gt;】
Catalog
Why is there dynamic memory allocation
Dynamic memory allocation function
Why is there dynamic memory allocation
When creating variables, you need to allocate memory space for variables , for example :
int a=10;
char arr[20]={0};The above methods are respectively on the stack area as a Variables open up 4 Bytes of space and opened up on the stack 20 Bytes of contiguous space , The size of the above development space depends on the type of variable , The size of the array when opening up space also depends on the number of elements and the type of elements , In some application scenarios, space cannot be allocated flexibly , And the life cycle of local variables is limited , When out of scope, it is destroyed .
In order to allocate memory more reasonably , Dynamic memory allocation is introduced , As its name , You can dynamically open up memory space on demand .
Four regions :
Dynamic memory allocation function
C Language provides some dynamic memory allocation functions that can open up memory space in the heap .
void* malloc (size_t size);//size_t It's a unsigned int type
This function can open up size Bytes of space , And return a pointer to the starting address of memory , The newly opened memory space is uninitialized , It stores uncertain values .
If size by 0, The return value of a function depends on how the function is implemented , At this time, the return value cannot be dereferenced ( Usually a null pointer ).
This function may also fail to apply for space , At this time, the null pointer is returned , Therefore, functions are usually used malloc After applying for a piece of memory space, you should judge whether the return value is empty .
When the heap space is used up, it needs to be released , Otherwise, there will be a memory leak when the program is running ( When the program ends normally, the space will be automatically released by the operating system )
At this time, it should be used with another function :
void free (void* ptr);
Its function is to free the space of dynamic memory allocation , If the space pointed to is not dynamically developed , The behavior is undefined .
If ptr Null pointer , This function does nothing .
Be careful : This function does not change ptr The pointer , therefore , The pointer also points to the original space ( It needs to be left empty manually , otherwise ptr It's a wild pointer )
The other two functions that open up dynamic memory :
void* calloc (size_t num, size_t size);
calloc Functions will be opened dynamically num The space of an array of elements , The space size of each element is size byte , And each element is initialized to 0, Therefore, a total of num*size Bytes of space .
If size by 0, This function does not necessarily return a null pointer ( Depends on the implementation of the Library ), Therefore, the return value cannot be dereferenced .
void* realloc (void* ptr, size_t size);
change ptr The size of the dynamic development memory pointed to , The size of the newly opened space is the size of the past and size The lesser of , If size Bigger , The content of the newly opened memory space is uncertain .
If ptr Is a null pointer , This function has the same function as malloc The same as .
(C90 By standard ,size by 0 Is a function, the same as free, Will return a null pointer ,C99 The null pointer is not necessarily returned under the standard )
If the space development fails, a null pointer will be returned , The original ptr The memory space pointed to will not be released ( The original space is effective , Will not be changed ).
Common dynamic memory errors
1. Dereference null pointer
void test()
{
int *p = (int *)malloc(INT_MAX/4);
*p = 20;// If p The value of is NULL, There will be problems
free(p);
}2. A cross-border visit
void test()
{
int i = 0;
int *p = (int *)malloc(10*sizeof(int));
if(NULL == p)
{
exit(-1);
}
*(p+10) = 11;// A cross-border visit
free(p);
}3.free Free non dynamically opened memory
void test()
{
int a = 10;
int *p = &a;
free(p);// error
}4.free Release a part of dynamic memory
void test()
{
int *p = (int *)malloc(100);
p++;
free(p);//p No longer point to the starting position of the space opened up by dynamic memory
}5, use free Release dynamically opened memory multiple times
void test()
{
int *p = (int *)malloc(100);
free(p);
free(p);// Repeat release
}6. Forget to free dynamically opened memory
void test()
{
int *p = (int *)malloc(100);
if(NULL != p)
{
*p = 20;
}
}
int main()
{
test();// Open dynamic memory space is not released
}Flexible array
C99 in , The last element in the structure is allowed to be an array of unknown size , This is called Flexible array member .
for example :
type_a *p = (type_a*)malloc(sizeof(type_a)+100*sizeof(int));
Is a flexible array a Opened up 4*100 Bytes of space , The memory opened up in this way is continuous
Support random access , Fast access , Less memory fragmentation .
p->i = 100;
for(int i = 0; i<100; i++) {
p->a[i] = i;
}
free(p);
边栏推荐
- 25.消息订阅与发布——PubSub-js
- [steering wheel] the super favorite idea efficiency artifact save actions is uninstalled
- Wild pointer, null pointer, invalid pointer
- My creation anniversary
- Chapter007 FPGA learning IIC bus EEPROM reading
- Unable to auto assemble, bean of type "redistemplate" not found
- Requests crawler implements a simple web page collector
- 24.全局事件总线
- QoS quality of service 4 traffic regulation of QoS boundary behavior
- win10声音图标有个没有声音
猜你喜欢

Three implementation methods of single sign on

Kali安装pip以及pip换源

Win10 sound icon has no sound

Vulnhub DC1

AMD64 (x86_64) architecture ABI document: upper

Learning strategies of 2D target detection overview (final chapter)
![[steering wheel] code review ability of idea to ensure code quality](/img/70/dec438ba57f9cbd5020bba5da652ba.png)
[steering wheel] code review ability of idea to ensure code quality

拉普拉斯(Laplace)分布

requests-爬取页面源码数据

FPGA realizes reading and writing of axi4 bus
随机推荐
OpenCascade笔记:gp包
CSDN, it's time to say goodbye!
全国职业院校技能大赛网络安全B模块 缓冲区溢出漏洞
JS的DOM操作——style的操作
UNI-APP_ Playback and pause of background music of applet or H5 page
二维平面多段线Y轴最短距离
Deep analysis of data storage in memory
B. Also Try Minecraft
Oauth2==SSO三种协议。Oauth2四种模式
MySQL语句
FlinkSQL-UDF自定义数据源
Kali installing PIP and pip source changing
File "manage.py", line 14) from exc ^ syntaxerror: cause and solution of invalid syntax error
nacos配置中心源码分析
China trichlorosilane Market Forecast and Strategic Research Report (2022 Edition)
[tips] a simple method to create a version control project
Gimp custom screenshot
Cloud version upgrade
Induction, generalization, deduction
UNI-APP_小程序或h5页面背景音乐的播放与暂停