当前位置:网站首页>Dynamic memory management knowledge points
Dynamic memory management knowledge points
2022-07-28 07:27:00 【Four years later.】
List of articles
Dynamic memory management
Why dynamic memory management exists ?
int a=10;// Open up four bytes on the stack space
char arr[10]= {
0};---- Open up on the stack space 10 Bytes of contiguous space
This is the way we currently know to open up space
1、 The size of the space is fixed
2、 When an array is declared , You must specify the length of the array , The memory it needs is allocated at the compilation stage
This fixed way of opening up space has limitations , It is inconvenient to carry out space maintenance later
Dynamic memory functions
#include<stdlib.h>
malloc
void* malloc (size_t size);
Allocate a memory block of one byte , Returns a pointer to the beginning of the block
1、 If the development is successful , Returns a pointer to the open space
2、 Applying for space may fail , If the development fails , Returns a null pointer , therefore malloc The return value of must be checked for validity
3、 The type of return value is void* type , therefore malloc Function doesn't know the type of open space , The specific time of use is determined by the user
int arr[10]={
0};
int *p = (int *)malloc(40);
if(p==NULL)
{
printf("%s\n",strerror(errno));
return 1;---- Historical habits :return 0 Is normal return ,return 1 Is the exception return
}
---- When the program exits , The system will automatically reclaim memory space , Is not to say that Memory space is not recycled
free
void free (void* ptr);
free Function is used to release dynamically opened memory
1、 If it's not dynamic memory , It's not enough free To release
2、 If parameters ptr Is a null pointer , Then the function will do nothing
free Is to release dynamically developed memory , However p Remember free Address of previous memory , But if you visit again at this time p Memory address pointed to , It will cause the problem of illegal space access , It turns into the problem of wild pointer , therefore , For dynamic development, after the memory is released , It is necessary to set null pointer .
calloc
void* calloc (size_t num, size_t size);
The function is to open up num Size is size Space
And malloc The difference between functions is calloc Each byte of the requested space will be initialized to 0
Which is the same thing as calloc = malloc +memset
To sum up , If you want to initialize the requested memory space , Just use calloc
If you don't want to initialize , Just use malloc
realloc
void* realloc (void* ptr, size_t size);
1、ptr For the memory address to be adjusted
2、size Is the adjusted new size
3、 The return value is the adjusted memory address
realloc There are two situations when the function adjusts the memory space
1、 There is not enough space behind the original space
2、 There is enough space behind the original space 1
int *ptr= malloc(20);
int *tmp =(int*) realloc(ptr,40);
1、 There is not enough space , Find a space of sufficient size elsewhere in the heap space , Copy the original data here 40 In a space of two bytes , And return to the starting address of the newly opened space

2、 There's enough space , Directly add 20 Bytes of space

Can't be used directly ptr To receive , If the space to be opened up is too large , There is no way to open up enough space on the pile ,realloc Function will return null pointer , like that ptr It becomes a null pointer , The previous space can't be found
Flexible array
stay C99 In the standard , The last element in the structure is allowed to be an array of unknown size
struct Stu
{
int i;
int arr[0];
}
In structure members , The last member is an array member of unknown size , And there is at least one element in front of the flexible array
When calculating the size , Only the sizes of other members in front of the flexible array are calculated
The characteristics of flexible arrays :
1、 The flexible array in the structure is preceded by at least one other member
2、sizeof The returned structure size does not include the memory of the flexible array
3、 Structures containing flexible array members should use malloc Function to dynamically allocate memory , And the allocated memory should be larger than the size of the structure , To fit the expected size of the flexible array
chestnuts :
struct Stu s;---- Do not create like this , In this case, it can only be stored 4 Bytes , No space for flexible arrays
The use of flexible arrays
int i=0;
struct Stu* p = (struct Stu*)malloc(sizeof(struct Stu)+10*sizeof(int));
if(p==NULL)
{
return 1;
}
p->i=100;
for(i=0;i<100;i++)
{
p->arr[i] = i;
}
free(p);
To obtain the 100 A continuous space of integer elements
How to be flexible ? Can pass realloc To maintain space
int i=0;
struct Stu* p = (struct Stu*)malloc(sizeof(struct Stu)+10*sizeof(int));
if(p==NULL)
{
return 1;
}
p->i=100;
for(i=0;i<10;i++)
{
p->arr[i] = i;
}
struct Stu* ptr = (struct Stu*)realloc(p,sizeof(struct Stu)+80);---- Capacity expansion
if(p!=NULL)
{
ps=ptr;
ptr=NULL;
}
free(ps);
ps=NULL;
That's for sure Someone asked , Why can't you just use int* Type pointer to maintain a dynamic memory space ?
struct S
{
int n;
int* arr;
};
int main()
{
struct S*ps = (struct S*)malloc(sizeof(struct S));---- Because the dynamically opened memory is in the heap , So we put int Variables of type are also created in the heap
if (ps == NULL)
{
return 1;
}
ps->n = 100;
ps->arr = (int*)malloc(40);
if (ps->arr == NULL)
{
//....
return 1;
}
// Use
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", ps->arr[i]);
}
// Capacity expansion
int*ptr = (int*)realloc(ps->arr, 80);
if (ptr == NULL)
{
return 1;
}
else
{
ps->arr = ptr;// Add : If the expansion is successful , Here's what I want to say ptr The value of is assigned to ps->arr, Space is still made up of ps->arr maintain
}
// Use
// Release
free(ps->arr);
free(ps);
ps = NULL;
return 0;
}
If you use int Type pointer opens up a space , The second method makes dynamic memory allocation twice , It's going on free When releasing the structure , The user releases the structure , But I don't know that members of this structure also need free, If we allocate the memory of the structure and the memory required by the members at one time , And return a structure pointer to the user , The user does it once free You can free up all the memory .
also , Do it many times malloc It will also cause memory fragmentation .
边栏推荐
- Shell -- first day homework
- Understanding of maximum likelihood estimation, gradient descent, linear regression and logistic regression
- vcf文件制作
- 面试中必不可少的性能优化专题~
- Shell --- conditional statement practice
- Softmax multi classification gradient derivation
- 移动端H5输入框调起手机软键盘,导致底部固定定位被顶起解决方法
- Isolation level RR, gap lock, unreal reading
- Redis哨兵模式及集群
- Short work priority SJF
猜你喜欢

大话持久性与redolog

指针进阶练习

How low-end computers learn secrets in depth - using the mistgpu computing platform

The "nuclear bomb level" log4j vulnerability is still widespread and has a continuing impact

Deeply analyze the implementation of singleton mode

js上传文件的方式

Serial port configuration of raspberry pie

Rsync+inotify to realize remote real-time synchronization

Tutorial (7.0) 06. Zero trust network access ztna * forticlient EMS * Fortinet network security expert NSE 5

Generate create table creation SQL statement according to excel
随机推荐
高响应比优先
C语言详解系列——数组详解,一维数组、二维数组
Image segmentation method
5G 商用第三年:无人驾驶的“上山”与“下海”
Safflower STL
Generate create table creation SQL statement according to excel
C language address book system
JS upload file method
高性能内存队列-Disruptor
Redis configuration and optimization of NoSQL
Deeply analyze the implementation of singleton mode
Serial port configuration of raspberry pie
vcf文件制作
Method of decomposing path into directory name and file name
nodejs操作MongoDB
Blueberry pie Bluetooth debugging process
教程篇(7.0) 06. 零信任网络访问ZTNA * FortiClient EMS * Fortinet 网络安全专家 NSE 5
uniapp 移动端 两种横竖屏切换方案
Redis哨兵模式及集群
Earliest deadline first (EDF)