当前位置:网站首页>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 .
边栏推荐
- 高性能内存队列-Disruptor
- Tutorial (7.0) 06. Zero trust network access ztna * forticlient EMS * Fortinet network security expert NSE 5
- A timed task reminder tool
- caffe fine tune
- 隔离级别RR、间隙锁、幻读
- Read the IP and device information of the switch node in the XML file, Ping the device, and the exception is displayed in the list
- Softmax multi classification gradient derivation
- JS upload file method
- TOPK problem
- Shell--- sed statement exercise
猜你喜欢
随机推荐
Method of decomposing path into directory name and file name
ELK日志分析系统的部署
C language address book system
232 (female) to 422 (male)
Record the first article of so and so Xiao Lu
Leetcode then a deep copy of the linked list
Safflower STL
Metasploit penetration MS7_ 010 exercise
Mysql查看某个表所占内存大小
“核弹级” Log4j 漏洞仍普遍存在,并造成持续影响
uniapp 移动端 两种横竖屏切换方案
High performance memory queue -disruptor
Install Nessus under Kali
4.1.4为什么要将成员变量设置为private
js上传文件的方式
LeNet5、AlexNet、VGGNet、ResNet
短作业优先SJF
guava之Retryer
VCF file production
map使用tuple实现多value值









