当前位置:网站首页>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 .
边栏推荐
- Available solution development oral arithmetic training machine / math treasure / children's oral arithmetic treasure / intelligent math treasure LCD LCD driver ic-vk1622 (lqfp64 package), original te
- STM32库函数进行GPIO初始化
- Tmall product details interface (APP, H5 end)
- info [email protected]: The platform “win32“ is incompatible with this module.
- Design and implementation of car query system based on php+mysql
- Obsidian installs third-party plug-ins - unable to load plug-ins
- STM32 library function for GPIO initialization
- < 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
- 大顶堆、小顶堆与堆排序
- PTA question bank== > complex four operations, one for one, examination seat number (7-73)
猜你喜欢
Factal: Unsafe repository is owned by someone else Solution
途家木鸟美团夏日折扣对垒,门槛低就一定香吗?
<口算练习机 方案开发原理图>口算练习机/口算宝/儿童数学宝/儿童计算器 LCD液晶显示驱动IC-VK1621B,提供技术支持
《可供方案开发》口算训练机/数学宝/儿童口算宝/智能数学宝 LCD液晶显示驱动IC-VK1622(LQFP64封装),原厂技术支持
Fabric. Usage of JS eraser (including recovery function)
什么是 eRDMA?丨科普漫画图解
[email protected]: The platform “win32“ is incompatible with this module."/>
info [email protected]: The platform “win32“ is incompatible with this module.
Implement a server with multi process concurrency
[development environment] StarUML tool (download software | StarUML installation | StarUML creation project)
Fabric.js 橡皮擦的用法(包含恢复功能)
随机推荐
The evolution process of the correct implementation principle of redis distributed lock and the summary of redison's actual combat
taobao.trade.get( 获取单笔交易的部分信息),淘宝店铺订单接口,淘宝oAuth2.0接口,淘宝R2接口代码对接分享
STM32 standard firmware library function name memory (II)
Advanced usage of C language -- function pointer: callback function; Conversion table
报错:npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.
Fabric.js 动态设置字号大小
1、编辑利器vim
Fabric.js 自由绘制圆形
检查密码
Fabric.js 手动加粗文本iText
Use of freemaker
STM32标准固件库函数名(一)
String matching problem
A white hole formed by antineutrons produced by particle accelerators
freemarker的使用
fatal: unsafe repository is owned by someone else 的解决方法
Talk about idempotent design
ONNX+TensorRT:将预处理操作写入ONNX并完成TRT部署
taobao. trade. Get (get some information of a single transaction), Taobao store order interface, Taobao oauth2.0 interface, Taobao R2 interface code docking and sharing
Using computed in uni app solves the abnormal display of data () value in tab switching