当前位置:网站首页>[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 .
边栏推荐
- How to use pixi.js to make simple Parkour games
- Sort out Huawei ap-3010dn_ V2 configuration create WiFi
- BGP border gateway protocol basic knowledge points
- The garbage classification data set used in the excellent Yolo target detection training is shared - about 3000 labeled
- uni-app - Refused to display ‘xxx‘ in a frame because an ancestor violates the following Content Sec
- Disable module (attribute node) in LabVIEW
- Django4.0 + Web + MySQL5.7 实现简单登录操作
- 图解LeetCode——1184. 公交站间的距离(难度:简单)
- How to realize the drop-down option box of wechat applet
- JS pop-up City filtering component matches mobile terminal
猜你喜欢

Druid 查询超时配置的探究 → DataSource 和 JdbcTemplate 的 queryTimeout 到底谁生效?

This is the worst controller layer code I've ever seen
![[graduation project] cinema booking management system based on micro Service Framework](/img/74/b12f1fe105c117aa96ebaa4226f85b.png)
[graduation project] cinema booking management system based on micro Service Framework

Do you know these methods of MySQL database optimization?

51 MCU peripherals: Motor

Why use MQ message oriented middleware? These questions must be taken down!

BGP border gateway protocol basic knowledge points

Redis/Mysql知识概述

How to choose a low code software development platform?

神经网络学习(1)前言介绍
随机推荐
图解LeetCode——919. 完全二叉树插入器(难度:中等)
Solutions to ten questions of leetcode database
Oracle10g单实例数据库升级到哪个版本好,求建议
Network principle (2) -- network development
51单片机内部外设:串口通信
Feiling ok1028a core board adapts to rtl8192cu WiFi module
艺术 NFT 的发展之路
How to connect tdengine with idea database tool?
What are the commands used by pl/sql tools to export SQL files?
Leetcode · 83 biweekly race · 6129. Number of all 0 subarrays · mathematics
优炫数据库对数据的加密是如何做的?
超赞的yolo目标检测训练所用垃圾分类数据集共享——标注好的约3000张
The annualization of financial products is 4%. How much profit can you get from buying 10000 yuan a month?
The hole of scroll view in uniapp
LeetCode·83双周赛·6129.全0子数组的数目·数学
图解LeetCode——1184. 公交站间的距离(难度:简单)
Canvas text JS special effect composed of many circles
[stl]list Simulation Implementation
Cool canvas animation shock wave JS special effect
Visual query (sp_helptext) -- quick query of stored procedures containing specified strings (with source code)