当前位置:网站首页>【C】 Dynamic memory management
【C】 Dynamic memory management
2022-07-18 21:41:00 【Domeecky】
Catalog
Dynamic memory functions
The space opened up by dynamic memory is stored in the heap , Programmers need to manually develop 、 Release .
All dynamic memory functions need to include header files <stdlib.h>
malloc
Full name :memory allocation
Apply to memory for a continuous available space ( Not initialized ), Returns a pointer to the space (void* type ), If the application fails , Return null pointer .
Because the application may fail , Therefore, it is necessary to judge whether the application is successful after application .
Because the returned pointer is void* type , Therefore, the pointer must be converted to the corresponding type before receiving .
usage :
int* a = NULL;// Receive the pointer of the requested space
a = (int*)malloc(40); Apply to memory 40 Byte space and convert to the corresponding type
if (a == NULL)// Judge whether the application fails
{
printf("%s\n", strerror(errno));// Print error messages
return;// End the function
}calloc
Full name :clear allocation
Apply to memory for a continuous available space ( And initialization ), Returns a pointer to the space (void* type ), If the application fails , Return null pointer .
usage :
int* a = NULL;// Receive the pointer of the requested space
a = (int*)calloc(4,10); Apply to memory 4 Space of elements , Every element 10 byte , common 40 byte
if (a == NULL)// Judge whether the application fails
{
printf("%s\n", strerror(errno));// Print error messages
return;// End the function
}realloc
Full name :reset allocation
Resize the requested space ( Not initialized ), If the adjustment is successful , Then return the pointer to the adjusted space (void* type ), If adjustment fails , Return null pointer .
Because adjustment may fail , Therefore, it is necessary to create intermediate variables to receive and judge .
usage :
int* a = NULL;
a = (int*)malloc(40);
if (!a)
{
printf("%s\n", strerror(errno));
return;
}
int* p = realloc(a, 10);// take a The pointing space is adjusted to 10 Bytes and assign to p
if (p != NULL)
a = p;// If p A pointer that is not null is assigned to a
There are two ways to increase the capacity of space :
(1) There is enough space for capacity expansion behind the original space , Then directly increase the capacity behind the original space , And return a pointer to the original space .
(2) There is not enough space for capacity expansion after the original space , Open up new space , Copy the original data , And return a pointer to the new space .

Reduce the volume of the space and return the pointer to the original space .
When adjusting space, a small amount of space may not be available , produce Memory fragments .
free
Release the requested space
When the dynamic memory is used up , The space must be released and returned to the system , Otherwise, a memory leak will occur .
Memory leak : After using the dynamically opened space , Not released or unable to release for some reason , Cause the program to slow down or crash .
Since the pointer still points to the space position after the space is released , To avoid illegal access , The pointer to this space must be set to null .
usage :
int* p = (int*)malloc(40);
free(p);// Release p Point to space
p = NULL;// take p empty practice ( Judge the running result of the following code )
(1)
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);
strcpy(str, "hello world");
printf(str);
}
int main()
{
Test();
return 0;
}answer : Memory leak ; Program crash
Memory leak caused by not releasing memory ; Pointer parameter transfer time , The address that you point to when delivering , because str Point to NULL, So pass it on to p after ,p It also points to NULL, Will not change str The direction of , When the str Conduct strcpy when , because str Null pointer , It cannot be modified , Cause the program to crash .
(2)
char *GetMemory(void)
{
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();
printf(str);
}
int main()
{
Test();
return 0;
}answer : Memory leak ; Print normal or random values
Memory leak caused by not releasing memory ; local variable p It is recycled after the function is generated , But the function returns p The address of , The space can be found according to the address , Because the space will not be initialized after recycling , Keep the original value , If the space has not been used , Print normally , If used , Then print random values .
(3)
void GetMemory(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");
printf(str);
}
int main()
{
Test();
return 0;
}answer : Memory leak ; Normal print
Memory leak caused by not releasing memory ;str For the pointer , So the introduction &str It must be received with a secondary pointer , Find str And point it to the application space , The last part strcpy And print .
(4)
void Test(void)
{
char *str = (char *) malloc(100);
strcpy(str, "hello");
free(str);
if(str != NULL)
{
strcpy(str, "world");
printf(str);
}
}
int main()
{
Test();
return 0;
}answer : Illegal access ; Normal print
free(str) after ,str It also points to the original space , Right now str Conduct strcpy, It changes the space that has been recycled .
Flexible array
An array in which the number of elements is not specified in the structure , And must be the last member , In the initial state, it does not occupy the space of the structure .
example :
struct S
{
int a;
int arr[];// Flexible array
}s;
int main()
{
sizeof(s);
return 0;
}result :4
usage :
struct S
{
int a;
int arr[];// Flexible array
}*s;
int main()
{
s = (struct S*)malloc(44);// front 4 bytes a Space , The rest is arr Space
return 0;
}边栏推荐
- 基于单片机倾角检测仪设计分享
- 一人用低代码开发平台搭建整个集团的数字化系统解决方案
- Do you know the answers to the common questions in the interview of senior programmers? With answer
- Phabricator Conduit API介绍
- 不同的图像patch由不同的专家模型来处理!南洋理工&Mila稀疏融合混合专家模型SF-MoE,具有超强泛化能力!代码已开源!...
- 机器学习笔记 - 使用 GAN 进行数据增强以进行缺陷检测
- MySQL -- string function
- [C language brush leetcode] 134 Gas station (m)
- (note sorting is not completed) [graph theory: minimum spanning tree]
- 多线程操作List
猜你喜欢

为什么网络安全在工厂中很重要?

Introduction to phabricator conduct API

Design and sharing of inclinometer based on single chip microcomputer

Why is network security important in factories?

Duplicate disk: how does the backpropagation process of pooling layer, average pooling and maximum pooling backpropagate

MySQL --- 多表查询 - 表与表之间的关系

Paddle crowdnet population density estimation

Installing MySQL database on Linux server (detailed tutorial)

Machine learning notes - data enhancement using Gan for defect detection

Redis - detailed explanation of slot management commands
随机推荐
On Relational operators in JS
I'm a little busy recently.
Build an enterprise level data governance system from 0 to 1!
[C language brush leetcode] 134 Gas station (m)
【黄啊码】MySQL入门—2、使用数据定义语言(DDL)操作数据库
Topic 2-iis write permission vulnerability analysis and traceability
[cache] introduction of a new cache caffeine cache
(note sorting is not completed) [graph theory: minimum spanning tree]
Daily question brushing record (XXV)
Leetcode+ 86 - 90 double pointer, backtracking, interval DP topics
网络空间对抗防御中的智能监测技术研究
Embedded development: seven techniques for accelerating firmware development
(笔记整理未完成)【图论:最小生成树】
阿普奇 E8 工控机——MinipiceCAN卡在建筑机器人的应用
音视频中的语音信号处理都包括哪些方向?
Phabricator Conduit API介绍
R language ggplot2 visualization: ggplot2 visualizes density plot and uses geom_ Vline function adds mean vertical line and mean value label (mean line or vertical line)
Do you know the answers to the common questions in the interview of senior programmers? With answer
【seaborn】5、Matrix plots 矩阵图
淺學js中的關系運算符