当前位置:网站首页>[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 .
边栏推荐
- Dark horse programmer JDBC
- JDBC quick start
- [Development Tutorial 9] crazy shell · open source Bluetooth smart health watch - storage
- How to realize the drop-down option box of wechat applet
- [graduation project] cinema booking management system based on micro Service Framework
- [deep learning] mask Dino Trilogy - the correct way to open Detr Pandora's box
- Redis learning notes
- OmniPeek packet capturing tool
- Sticky.js page scrolling div fixed position plug-in
- 为什么说DAO是未来的公司形式
猜你喜欢

How to connect tdengine with idea database tool?

Comparison between symmetric encryption and asymmetric encryption

51 MCU peripherals: Motor
![[deep learning] mask Dino Trilogy - the correct way to open Detr Pandora's box](/img/5c/52ccc0583451eba15fec18adb1499e.png)
[deep learning] mask Dino Trilogy - the correct way to open Detr Pandora's box

js触屏小游戏源码冰雪之旅
![[Development Tutorial 9] crazy shell · open source Bluetooth smart health watch - storage](/img/25/212712d919540763a6c339e1b5a50b.png)
[Development Tutorial 9] crazy shell · open source Bluetooth smart health watch - storage

Arrange the array into the smallest number

sticksy.js页面滚动div固定位置插件

JS pop-up City filtering component matches mobile terminal
![[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
随机推荐
Ctfhub skill tree Web
[NPM] the "NPM" item cannot be recognized as the name of cmdlets, functions, script files or runnable programs. Please check the spelling of the name. If the path is included, make sure the path is co
activemq--可持久化机制之KahaDB
Canvas text JS special effect composed of many circles
51 MCU peripherals: Motor
table表格展开内部行切换效果
防抖与节流
360度拖拽全景图插件tpanorama.js
[hero planet July training leetcode problem solving daily] 19th binary tree
Labview--- signal generator
对称式加密与非对称式加密的对比
51单片机内部外设:定时器和计数器
Wechat sports ground reservation applet graduation project of applet completion works (1) development outline
超赞的yolo目标检测训练所用垃圾分类数据集共享——标注好的约3000张
Canvas dynamic picture avatar shaking JS special effect
The operation cannot be completed because a folder or file in it is already open in another program
[graduation project] cinema booking management system based on micro Service Framework
Django4.0 + web + MySQL 5.7 realize simple login operation
uniapp中scroll-view的坑
Additional: SQL statement area / county in the lower half (data table)