当前位置:网站首页>Dynamic memory management
Dynamic memory management
2022-06-30 07:20:00 【There are fish in Beiming】
Dynamic memory management
1. Why is there dynamic memory allocation
The ways we have mastered to open up the continuous memory space are :
char arr[10] = {
0};// Open up on the stack space 10 Bytes of contiguous space
The above-mentioned way of opening up space has a very obvious defect , When an array is declared , You must specify the length of the array , The memory it needs is allocated at compile time , The space opened up is fixed , It may be too big , It may be small , It is difficult to meet our actual needs . At this point, you can only try dynamic memory allocation .
2. The introduction of dynamic memory function
We know that memory can be divided into bit stack areas , Heap area , Static storage area , The stack area mainly stores local variables and formal parameters , And we malloc,calloc,realloc The dynamically requested memory space is opened up in the heap area , meanwhile free The memory space released by the function is also the memory space of the heap , The static storage area mainly stores static variables and global variables .
Let's go into the dynamic memory function used to dynamically request space in the heap malloc,calloc,realloc.
(1)malloc and free
malloc The function is C Language provides a dynamic memory allocation function , Its prototype is void * malloc (size_t size);
This function applies to memory for a contiguous block of free space , And return the pointer to this space . If the development is successful , Returns a pointer to the opened space . If the development fails , Returns a NULL The pointer , therefore malloc The return value of must be checked . such as :
// Use malloc Function applied for a piece of memory space , Let the pointer ptr Point to this memory space
ptr = (int*)malloc(num*sizeof(int));
// Later we want to use ptr when , Be sure to check if it is NULL
if(NULL != ptr)
{
......
}
The type of return value is void* , Because malloc Function doesn't know the type of open space , The user will decide when using it .
If parameters size by 0,malloc The standard of behavior is undefined , It depends on the compiler .
C Language provides another function free, It is specially used for dynamic memory release and recovery , The function prototype is void free (void * ptr);
free Function is used to release memory opened dynamically . If parameters ptr The pointed space is not opened dynamically , that free The behavior of a function is undefined . If parameters ptr yes NULL The pointer , be free Functions do nothing .
It is worth noting that , Use free Function frees up the space for dynamic application , The pointer still holds the address of this space , That's the wild pointer , That is, we can still access the memory that has been reclaimed by the system through the pointer , But this constitutes illegal access , To avoid such illegal access , After we free this memory space , To assign a pointer to NULL.
free(ptr);
ptr = NULL;
notes :
Stack variables are automatically recycled , There is no need for us to manually release , Only malloc,calloc,realloc Dynamic application memory space is required free.
(2)calloc
calloc Function is also used for dynamic memory allocation , Its function prototype is void* calloc (size_t num, size_t size);
The function is for num Size is size The elements of open up a space , And initialize each byte of the space to 0. And functions malloc The only difference is calloc Initializes each byte of the requested space to full before returning the address 0.
So if we need to initialize the content of the memory space applied , Then you can use calloc Function is very convenient to complete the task .
(3)realloc
realloc Functions make dynamic memory management more flexible .
Sometimes we find that the application space is too small in the past , Sometimes we think the application space is too large , In order to make rational use of memory , We must flexibly adjust the size of the memory , that realloc Function can be used to adjust the dynamic memory size . The function prototype is :
void* realloc (void* ptr, size_t size); among ptr Is the memory address to be adjusted ,size Is the new size after adjustment , The return value is the starting memory position after adjustment .
realloc There are two situations when adjusting memory space :
situation 1: There is enough space behind the original space
situation 2: There is not enough space after the original space
When it's the case 1 When , To expand memory, add space directly after the original memory , The original spatial data does not change . When it's the case 2 When , There is not enough space after the original space , The way to expand is : Open up another continuous space of appropriate size on the heap space to use , At this time, the function will copy the data in the original memory to the newly opened space , This function returns a new memory address .
Of course, in addition to the above two cases , There's a third situation , Namely realloc The function failed to open up space and returned NULL, Because of the third situation ,realloc We should pay attention to the use of functions . for instance :
#include <stdio.h>
int main()
{
int *ptr = malloc(100);
if(ptr != NULL)
{
// Business processing
}
else
{
exit(EXIT_FAILURE);
}
// Expand capacity
// Code 1
ptr = realloc(ptr, 1000);// Is this ok? ?
Obviously, according to the above code 1 It is not advisable to write , because ptr It originally pointed to a piece of malloc Function opens up space , If realloc Function adjustment space failed , return NULL By ptr To receive the , that ptr The value is NULL, This leads me not only to fail to adjust the space , Even the space I pointed to was lost , In order to avoid this kind of situation, I lost my wife and lost my soldiers , We should make the code more rigorous .
// Code 2
int*p = NULL;
// Let's start with a pointer p To receive the return value
p = realloc(ptr, 1000);
if(p != NULL)
{
// Confirm that the return value is not NULL after , We assign it to ptr
ptr = p;
}
// Business processing
free(ptr);
return 0;
}
It should be noted that ,realloc The message is NULL, The function is the same as malloc The function is the same , Directly open up a specified size of space , So realloc Space can be adjusted , It can also be like malloc Just like opening up space .
边栏推荐
- Qtcreator debug code after configuring CDB debugger view variable value display card
- [introduction to Expo application] v Expert recommendation letter template
- Linux server installation redis
- halcon:读取摄像头并二值化
- 02 - bare metal and RTOS development modes: five development modes of bare metal and the introduction of RTOS
- Nested if statement in sum function in SQL Server2005
- 网络安全-三层交换技术和内部网络规划
- Deploying web projects using idea
- Four great happenings on earth
- What if I don't know what to do after graduating from university?
猜你喜欢
我今年毕业,但我不知道我要做什么
Pit stepping record: Supervisor log return information: redis extension is not installed
How to use string branches for switch case
Introduction to go language pointer
Linux server installation redis
nRF52832 GPIO LED
SQL Server2005中SUM函数内嵌套IF语句
Cubemx completes STM32F103 dual serial port 485 transceiver transmission
网络安全-抓包和IP包头分析
Keil plug-in Usage Summary
随机推荐
What does the real name free domain name mean?
uniapp图片下方加标签标图片
Introduction to go language pointer
nRF52832 GPIO LED
对占用多字节和位的报文信号解析详解
Idea running run and services
Base64 encoding method implemented by native JS
Network security - layer 3 switching technology and internal network planning
大学刚毕业不知道做什么工作怎么办?
js创建pdf文件
QT common macro definitions
Use of ecostruxure (3) creating composite function blocks
MAX6675 usage notes
【最全】linux服务器上安装Mysql
[docsify basic use]
Thread network
解决:div获取不到键盘事件
Network security - routing principle
Swiftui creates a beautiful custom press feedback button
Minecraft 1.16.5模组开发(五十) 书籍词典 (Guide Book)