当前位置:网站首页>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 .
边栏推荐
- 单测调用对象的私有方法
- 28 rounds of interviews with 10 companies in two and a half years
- 年轻人搞副业有多疯狂:月薪3000,副业收入3W
- 安装Go语言开发工具
- Linu foundation - zoning planning and use
- Install go language development tools
- Qstring to const char*
- 网络安全-VLAN和Tunk方法详解
- Daemon and user threads
- How crazy are young people in sideline industry: 3000 monthly salary and 3W sideline income
猜你喜欢

Resolution: div failed to get keyboard event

Qtcreator debug code after configuring CDB debugger view variable value display card

The class imported by idea import clearly exists, but it is red?

Variable storage unit and pointer

Go common commands

Keil plug-in Usage Summary

踩坑记录:supervisor 日志返回信息:redis扩展未安装

MySQL encounters the problem of expression 1 of select list is not in group by claim and contains nonaggre

Introduction to go language pointer

大学刚毕业不知道做什么工作怎么办?
随机推荐
01 - embedded learning route and career planning: embedded basic knowledge and development process
Base64 encoding method implemented by native JS
大学刚毕业不知道做什么工作怎么办?
[resolved] MySQL exception: error 1045 (28000): unknown error 1045, forgetting the initial password
线程池——C语言
Traverse map
视频播放器(二):视频解码
Introduction to go project directory structure
Swiftui creates a beautiful custom press feedback button
TC397 QSPI(CPU)
2021-07-02
我今年毕业,但我不知道我要做什么
grep命令用法
Variable storage unit and pointer
安装Go语言开发工具
网络安全-路由原理
Out of class implementation of member function of class template
实验一、综合实验【Process on】
Linux服務器安裝Redis
Qdebug small details