当前位置:网站首页>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 .
边栏推荐
- Fabric. JS free draw circle
- A white hole formed by antineutrons produced by particle accelerators
- Design and implementation of car query system based on php+mysql
- 跨服务器数据访问的创建链接服务器方法
- OpenHarmony笔记-----------(四)
- Fabric.js 自由绘制椭圆
- 富文本编辑器添加矢量公式(MathType for TinyMCE ,可视化添加)
- Teamtalk source code analysis win client
- 什么是 eRDMA?丨科普漫画图解
- obsidian安装第三方插件——无法加载插件
猜你喜欢

<口算練習機 方案開發原理圖>口算練習機/口算寶/兒童數學寶/兒童計算器 LCD液晶顯示驅動IC-VK1621B,提供技術支持

What is erdma? Popular science cartoon illustration

jmeter脚本参数化

There is no solution to the decryption error of the remote user 'sa' and the service master password mapped from the remote server 'to the local user' (null) /sa '

How kaggle uses utility script

Makefile separates file names and suffixes

快解析:轻松实现共享上网

Obsidian installs third-party plug-ins - unable to load plug-ins

【空间&单细胞组学】第1期:单细胞结合空间转录组研究PDAC肿瘤微环境

taobao. trade. memo. Add (add remarks to a transaction) interface, Taobao store flag insertion interface, Taobao order flag insertion API interface, oauth2.0 interface
随机推荐
taobao.trade.get( 获取单笔交易的部分信息),淘宝店铺订单接口,淘宝oAuth2.0接口,淘宝R2接口代码对接分享
tmall. product. schema. Get (product information acquisition schema acquisition), Taobao store upload commodity API interface, Taobao commodity publishing interface, Taobao commodity upload API interf
taobao.logistics.dummy.send( 无需物流发货处理 )接口,淘宝店铺发货API接口,淘宝订单发货接口,淘宝r2接口,淘宝oAu2.0接口
Fabric.js 自由绘制椭圆
Openharmony notes --------- (4)
uniapp自动化测试学习
没有从远程服务器‘‘映射到本地用户‘(null)/sa‘的远程用户‘sa‘及服务主密码解密错误的解决办法
PHP linked list creation and traversal
STM32 library function for GPIO initialization
字符串匹配问题
Fabric.js 上划线、中划线(删除线)、下划线
Reuse and distribution
docker mysql
Xilinx Vivado set *.svh as SystemVerilog Header
Talk about idempotent design
The most complete analysis of Flink frame window function
Fabric. JS free drawing ellipse
富文本编辑器添加矢量公式(MathType for TinyMCE ,可视化添加)
STM32 standard firmware library function name (I)
C#代码审计实战+前置知识