当前位置:网站首页>Advanced C language (learn malloc & calloc & realloc & free in simple dynamic memory management)
Advanced C language (learn malloc & calloc & realloc & free in simple dynamic memory management)
2022-07-02 14:43:00 【K-mate】
Catalog
One 、 Why is there dynamic memory allocation
Two 、 Use of dynamic memory functions
(2)malloc Function considerations
(1)calloc Definition of function
(1)realloc Definition of function
(2)realloc Function considerations
One 、 Why is there dynamic memory allocation
stay c The memory development methods we currently master in the language are :
int val = 20;// Open up four bytes in the stack space
char arr[10] = {0};// Open up on the stack space 10 Bytes of contiguous space
Or create a variable , Or create an array .
The space created in this way sometimes appears when we use it, or we feel that the space is too large , Or I feel the space is too small , inflexible .
So we need a way to make space bigger and smaller , At this time, dynamic memory development appears .But there are two characteristics of the way to open up space :
1. The size of the space opening is fixed .
2. Arrays are declared , You must specify the length of the array , The memory it needs is allocated at compile time . But the need for space , It's not just that . Sometimes the amount of space we need is known when the program is running , The way to open up space when compiling arrays is not enough . At this time, you can only try dynamic storage development .
Two 、 Use of dynamic memory functions
First of all, we need to understand the data , Variable , How functions are stored in memory , As shown in the figure below :

1.malloc function
(1)malloc The definition of
This function applies to memory for a contiguous block of free space , And return the pointer to this space .
(2)malloc Function considerations
1. If the development is successful , Then return a pointer to open a good space .
2. If the development fails , Returns a NULL The pointer , therefore malloc The return value of must be checked .
3. The type of return value is void* , therefore malloc Function doesn't know the type of open space , Specifically, when using, the user himself To decide .
4. If parameters size by 0,malloc The standard is undefined , Depends on the compiler .
(3)malloc Use of functions
The code is as follows :
#include<stdio.h>
// Dynamic memory development
int main()
{
// Suppose you open ten integer spaces -- 10*sizeof(int)
int arr[10];// The stack area
// Dynamic memory development
int* p = (int*)malloc(10 * sizeof(int));
// When using these spaces
if (p == NULL)
{
perror("main");//main:xxxxxxxxxxx( error message )
}
// Use
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = i;
}
for (i = 0; i < 10; i++)
{
printf("%d", p[i]);//p[i]-->*(p + i)
}
// Recycle space
free(p);//malloc Functions should match free Function USES , After use, take the initiative to release this space
p = NULL;// After the release, put p Set to null pointer
return 0;
}2.calloc function
(1)calloc Definition of function
C The language also provides a function called calloc , calloc Function is also used for dynamic memory allocation .

(2)calloc Function considerations
1. The function is for num Size is size The elements of open up a space , And initialize each byte of the space to 0.
2. And functions malloc The only difference is calloc Initializes each byte of the requested space to full before returning the address 0.
(3)calloc Use of functions
The code is as follows :
#include<stdio.h>
// Dynamic memory development
int main()
{
int* p = calloc(10,sizeof(int));
// When using these spaces
if (p == NULL)
{
return 1;
}
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d", p[i]);//p[i]-->*(p + i)
}
// Recycle space
free(p);//malloc Functions should match free Function USES , After use, take the initiative to release this space
p = NULL;// After the release, put p Set to null pointer
return 0;
}The results are as follows :

It should be noted that ,calloc Functions and malloc There are two differences between functions ,
1.calloc The parameters of the function are two ,malloc The argument to the function is a .
2.malloc If the function is not initialized, all the printed values are random ,calloc Functions do not need to be initialized , By default, each byte of the requested space will be initialized to 0.
3.realloc function
(1)realloc Definition of function
realloc Functions make dynamic memory management more flexible .
Sometimes we find that the application space is too small in the past , Sometimes we think the application space is too large , That's for a reasonable time Waiting memory , We will make flexible adjustments to the size of memory .
that realloc Function can be used to dynamically open up the memory size Adjustment of .

(2)realloc Function considerations
1.ptr Is the memory address to be adjusted
2.size New size after adjustment The return value is the starting memory position after adjustment .
3. This function adjusts the size of the original memory space , The original data in memory will also be moved to new Space .
4.realloc There are two ways to adjust memory space :
situation 1 When it's the case 1 When , To expand memory, add space directly after the original memory , The original spatial data does not change .
situation 2 When it's the case 2 When , When there is not enough space after the original space , The way to expand is : Find another suitable size on the heap space Continuous space to use . This function returns a new memory address . Because of the above two situations ,realloc We should pay attention to the use of functions .
(3)realloc Use of functions
#include<stdio.h>
// Dynamic memory development
int main()
{
int* p = calloc(10,sizeof(int));
// When using these spaces
if (p == NULL)
{
perror("main");
return 1;
}
int i = 0;
for (i = 0; i < 10; i++)
{
*(p + i) = 5;
}// Need here P Point to more space , need 20 individual int The size of the space
//realloc Resize space
int* ptr = realloc(p, 20 * sizeof(int*));
if (ptr != NULL)
{
p = ptr;
}
// Recycle space
free(p);//malloc Functions should match free Function USES , After use, take the initiative to release this space
p = NULL;// After the release, put p Set to null pointer
return 0;
}summary
This article simply introduces the definition of dynamic memory function , Precautions and use , also free Function is used to free the space opened up by dynamic memory , Then set it to empty . If there are any questions in the article , You are welcome to ask questions . I will study and correct with an open mind , The most important thing is to make progress together , Grow up together , Learn programming well .
边栏推荐
猜你喜欢

《可供方案开发》口算训练机/数学宝/儿童口算宝/智能数学宝 LCD液晶显示驱动IC-VK1622(LQFP64封装),原厂技术支持

Thoroughly master prototype__ proto__、 Relationship before constructor (JS prototype, prototype chain)

YoloV6训练:训练自己数据集遇到的各种问题

Stm32-dac Experiment & high frequency DAC output test

socket(套接字)与socket地址

Makefile 分隔文件名与后缀

Method of creating linked server for cross server data access

ONNX+TensorRT:将预处理操作写入ONNX并完成TRT部署

< schéma de développement de la machine d'exercice oral > machine d'exercice oral / trésor d'exercice oral / trésor de mathématiques pour enfants / lecteur LCD de calculatrice pour enfants IC - vk1621

MQ tutorial | exchange (switch)
随机推荐
博睿数据一体化智能可观测平台入选中国信通院2022年“云原生产品名录”
mathML转latex
PTA question bank== > complex four operations, one for one, examination seat number (7-73)
C语言高级用法--函数指针:回调函数;转换表
Advanced usage of C language -- function pointer: callback function; Conversion table
Fabric. Usage of JS eraser (including recovery function)
Pycharm连接远程服务器
threejs的控制器 立方體空間 基本控制器+慣性控制+飛行控制
PyQt5_ Qscrollarea content is saved as a picture
STM32 standard firmware library function name memory (II)
Fabric. JS manual bold text iText
taobao.trade.get( 获取单笔交易的部分信息),淘宝店铺订单接口,淘宝oAuth2.0接口,淘宝R2接口代码对接分享
Solving the longest subsequence with linear DP -- three questions
The evolution process of the correct implementation principle of redis distributed lock and the summary of redison's actual combat
STM32 standard firmware library function name (I)
< schematic diagram of oral arithmetic exercise machine program development> oral arithmetic exercise machine / oral arithmetic treasure / children's math treasure / children's calculator LCD LCD driv
Makefile separates file names and suffixes
卷积神经网络(入门)
Borui data integrated intelligent observable platform was selected into the "Yunyuan production catalogue" of China Academy of communications in 2022
Delete element (with transition animation)