当前位置:网站首页>[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 .
边栏推荐
- 2022-7-14 JMeter pressure test
- 51 single chip microcomputer controls nixie tube display
- C语言实现二叉平衡树
- Redis learning notes
- Labview--- signal generator
- 附加:中半部分sql语句 区/县(数据表)
- 28. Slot
- Why use MQ message oriented middleware? These questions must be taken down!
- Live broadcast preview | how to build an enterprise cloud management platform in the cloudy era?
- How does Youxuan database encrypt data?
猜你喜欢
![[arm] Xintang nuc977 transplants wk2124 drive](/img/0c/fa21d7a44e0263dde4d3135a78818f.png)
[arm] Xintang nuc977 transplants wk2124 drive

What version of Oracle10g single instance database is better to upgrade to? Ask for suggestions

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

这家十年内容产业基建公司,竟是隐形的Web3先行者

整理 华为AP-3010DN_V2配置创建wifi

Troubleshooting error: NPM install emojis list failed

Django4.0 + web + MySQL 5.7 realize simple login operation

Unity ugui interaction (new ideas)

Opencv realizes simple face tracking

sql注入
随机推荐
Learning Weekly - total issue 63 - an open source local code snippet management tool
Wechat sports ground reservation applet graduation project of applet completion works (1) development outline
Yolov5 environment configuration
Disable module (attribute node) in LabVIEW
Feiling ok1028a core board adapts to rtl8192cu WiFi module
LabVIEW experiment - temperature detection system (experimental learning version)
为什么说DAO是未来的公司形式
canvas动态图片头像晃动js特效
Redis-哨兵,主从部署详细篇
Wechat sports ground reservation applet graduation design of applet completion works (3) background function
Silicon Valley classroom lesson 12 - official account on demand course and live broadcast management module
Anti shake and throttling
JDBC的API解析
Query efficiency increased by 10 times! Three optimization schemes to help you solve the deep paging problem of MySQL
The international summit osdi included Taobao system papers for the first time, and end cloud collaborative intelligence was recommended by the keynote speech of the conference
(self drawn ugly picture) simple understanding tcp/ip three handshakes and four waves
Comments on specific applications of camera
[hero planet July training leetcode problem solving daily] 19th binary tree
API parsing of JDBC
Comparison between symmetric encryption and asymmetric encryption