当前位置:网站首页>[C language] dynamic memory management, flexible array
[C language] dynamic memory management, flexible array
2022-07-25 09:16:00 【Jiang Lingyu's daily account】


1、realloc Situation during capacity expansion :
2、realloc Can also be realized malloc function
5、 ... and 、 Common errors in using dynamic memory
2、 Cross border access to dynamically opened space
3、 For non dynamic development content free
4、 only free Part of dynamic development space
5、 Multiple times for the same block of memory free
6、 Dynamic memory space forgot to release ( Memory leak )
2、 The characteristics of flexible arrays
3、 Usage scenarios of flexible arrays
4、 Advantages of flexible arrays
One 、malloc

This function requests a continuous space from the heap , And return the address of this memory .
int main()
{
int* p = (int*)malloc(40);
if (p == NULL)
{
printf("%s\n", strerror(errno));
return 1;
}
free(p);
p = NULL;
return 0;
}If the development fails , Returns a NULL The pointer , therefore malloc The return value of must be checked .
If parameters size by 0,malloc The standard is undefined , Depends on the compiler .
Two 、free

free Function is used to release memory opened dynamically .free The pointer to must be the starting address of the dynamic memory space .
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 , Then the function does nothing .
3、 ... and 、calloc

num: The number of elements to be dynamically developed
size: The size of each element

calloc=malloc+memset
calloc and malloc The difference is calloc The space opened by dynamic memory will be initialized to 0
Four 、realloc

ptr: The original address that needs to be expanded
size: Total size after expansion
1、realloc Situation during capacity expansion :
1、 There is enough space in the rear when expanding , Will continue to expand in the rear , Return to the original address
2、 The rear space has been used when expanding , It will be expanded in a new area , And copy the original data to the new area ,free The memory pointed to by the original address , And return the address of the memory block .
3、 The space is insufficient , Can't expand , Return null pointer
2、realloc Can also be realized malloc function
int main()
{
int* p = (int*)realloc(NULL, 40);
return 0;
}realloc When malloc When using , Pass the null pointer to the first parameter .
5、 ... and 、 Common errors in using dynamic memory
1、free Null pointer
void text()
{
int* p = (int*)realloc(NULL, 40);
if (p == NULL)// Judge p Null pointer or not
{
return;
}
*p = 20;
}If you open up space , No judgment pointer p Whether it is a null pointer , If dynamic memory development fails , that *p Will dereference null pointer .
2、 Cross border access to dynamically opened space
void text()
{
int* p = (int*)realloc(NULL, 40);
int* m = p;
if (p == NULL)
{
return;
}
for (int i = 0; i <= 10; i++)
{
p[i] = i;// Transboundary
p++;
}
}3、 For non dynamic development content free
void text()
{
int arr[] = {1,2,3};
int* p = arr;
free(p);// It is not allowed to conduct free
}4、 only free Part of dynamic development space
void text()
{
int* p = (int*)malloc(40);
p++;
free(p);//p No longer point to the starting position of dynamic opening space
}When actually writing code, you still have to pay more attention to this situation , The pointer p It is no longer the initial position in the process of use ,free(p) It will break down .
5、 Multiple times for the same block of memory free
void text()
{
int* p = (int*)realloc(NULL, 40);
free(p);
//p = NULL;
free(p);
}free(p) After that, the p Set to null pointer , Even if the p Many times free Also no problem .
6、 Dynamic memory space forgot to release ( Memory leak )
void text()
{
int* p = (int*)realloc(NULL, 40);
int a = 0;
scanf("%d", &a);
if (a == 5)
return;
free(p);
p = NULL;
}When the function terminates in advance , There is no chance to go to free, May cause memory leaks
Another possibility is to call the function of dynamically opening up memory , The user is not doing it externally free
6、 ... and 、 Flexible array
1、 Concept of flexible array
C99 in , The last member variable in the structure can be an array of unknown size
struct S
{
int a;
int arr[0];// there arr[0] Represents an array of unknown size
};
// Or as follows :
struct S
{
int a;
int arr[];
};2、 The characteristics of flexible arrays
A flexible array member in a structure must be preceded by at least one other member .
sizeof The size of the structure returned does not include the memory of the flexible array .
Structures that contain flexible array members 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 .
3、 Usage scenarios of flexible arrays
scene : Open all member variables in the structure in the heap
Use flexible arrays :
struct S
{
int a;
int arr[0];
};
int main()
{
struct S s;
struct S* ps = &s;
ps = (struct S*)realloc(NULL,sizeof(s) + 40);// Opening up space for the first time , Pass on NULL
if (ps == NULL)
{
exit(-1);
}
free(ps);
ps = NULL;
return 0;
}Pay attention to realloc The first parameter passed in is NULL instead of &s, Pass in &s It will break down , Because this is the first dynamic memory development , Here comes NULL It is equivalent to using malloc
After completing the development s The storage in memory is shown in the figure below :

Use regular structures :
struct S
{
int a;
int* parr;
};
int main()
{
struct S* p = (struct S*)malloc(sizeof(struct S));// Dynamically open up space for the structure
if (p == NULL)
{
exit(-1);
}
int* tmp= (int*)malloc(sizeof(int) * 2);// Dynamically open up a space in the stack area
if (tmp == NULL)
{
exit(-1);
}
p->parr = tmp;
free(p->parr);// On release , Need to release first p->parr Point to space
p->parr = NULL;
free(p);// Then the structure pointer p The space pointed to is released
p = NULL;
return 0;
}After completing the development s The storage in memory is shown in the figure below :

4、 Advantages of flexible arrays
1、 Under the above conditions , Use flexible arrays to facilitate dynamic memory release . If our code is in a function for others , You do a secondary memory allocation in it , And return the whole structure to the user . The user calls free You can release the structure , But the user doesn't know that the members in the structure also need free, May cause memory leaks . therefore , If we allocate the memory of the structure and its 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 .
2、 Continuous memory is good for improving access speed , It also helps reduce memory fragmentation .
边栏推荐
- Common tool classes under JUC package
- This is the worst controller layer code I've ever seen
- Leetcode · 83 biweekly race · 6129. Number of all 0 subarrays · mathematics
- Silicon Valley classroom lesson 15 - Tencent cloud deployment
- 51 single chip microcomputer controls nixie tube display
- leetcode-238.除自身以外数组的乘积
- Sticky.js page scrolling div fixed position plug-in
- [stl]stack & queue simulation implementation
- Comparison between symmetric encryption and asymmetric encryption
- A picture to quickly understand envoyfilter in istio
猜你喜欢

mysql中的数据结果排名

CIR industrial automation radar

Wechat sports field reservation of the finished works of the applet graduation project (4) opening report

Unity ugui interaction (new ideas)
![[machine learning] Finally, the important steps of machine learning modeling have been clarified](/img/75/07767ed694502f0c910d35e1447499.jpg)
[machine learning] Finally, the important steps of machine learning modeling have been clarified

What is steel grating?

Troubleshooting error: NPM install emojis list failed

2022-7-14 JMeter simulates the login of different users for pressure test

The operation cannot be completed because a folder or file in it is already open in another program

51 single chip microcomputer key control LED light status
随机推荐
Neural network learning (1) Introduction
51单片机外设篇:蜂鸣器
Django4.0 + Web + MySQL5.7 实现简单登录操作
艺术 NFT 的发展之路
Django4.0 + web + MySQL 5.7 realize simple login operation
SQL injection
[deep learning] overview | the latest progress of deep learning
The garbage classification data set used in the excellent Yolo target detection training is shared - about 3000 labeled
JMeter test plan cannot be saved solution
js触屏小游戏源码冰雪之旅
360 degree drag panorama plug-in tpanorama.js
神经网络学习(1)前言介绍
51单片机内部外设:串口通信
[STL]list模拟实现
为什么说DAO是未来的公司形式
activemq--可持久化机制之AMQ
[deep learning] mask Dino Trilogy - the correct way to open Detr Pandora's box
Learning Weekly - total issue 63 - an open source local code snippet management tool
机器人跳跃问题
Silicon Valley classroom lesson 15 - Tencent cloud deployment