当前位置:网站首页>动态内存管理
动态内存管理
2022-07-23 05:04:00 【VisionaryHS】

- 首先了解malloc函数的数据类型:1.返回值为void*指针,参数为无符号整型 size_t,size表示你需要开辟的空间的大小,单位为字节
- 注意事项: 如果开辟成功,则返回一个指向开辟好空间的指针。如果开辟失败,则返回一个NULL指针,因此malloc的返回值一定要做检查。返回值的类型是 void* ,所以malloc函数并不知道开辟空间的类型,具体在使用的时候使用者自己来决定。malloc声明在 stdlib.h 头文件中如果参数 size 为0,malloc的行为是标准是未定义的,取决于编译器。最好别让size为0;
- 使用完malloc函数后记得用free函数释放所指向的空间;
free函数
- free函数的作用:free函数用来释放动态开辟的内存。
- 如果参数 ptr 指向的空间不是动态开辟的,那free函数的行为是未定义的。如果参数 ptr 是NULL指针,则函数什么事都不做。
- free声明在 stdlib.h 头文件中
- 具体使用情况如下:
#include <stdio.h> int main() { //代码1 int num = 0; scanf("%d", &num); int arr[num] = {0}; //代码2 int* ptr = NULL; ptr = (int*)malloc(num*sizeof(int)); if(NULL != ptr)//判断ptr指针是否为空 { int i = 0; for(i=0; i<num; i++) { *(ptr+i) = 0; } } free(ptr);//释放ptr所指向的动态内存 ptr = NULL;//是否有必要? return 0; }最后将指针ptr置成NULL非常必要,否则会造成野指针。
calloc函数

- calloc的返回值也是void*,参数是两个无符号整型,num表示需要开辟几个单位的空间,而size表示单位空间的大小,单位是字节,并且把空间的每个字节初始化为0。;例如,我想要开辟40个字节的空间,可令num=10,size=4,所开辟空间的大小等于num*size。
- malloc和calloc的区别就是,calloc在开辟空间的同时,也把所申请的空间的每个字节都初始化为零。
- 其他的作用和malloc基本一致

realloc函数

参数中ptr指针指向的要调整的内存地址,
size 调整之后新大小
返回值为调整之后的内存起始位置。这个函数调整原内存空间大小的基础上,还会将原来内存中的数据移动到 新的空间。- realloc在调整内存空间的是存在两种情况:
- 1.原有空间够大
- 2.原有空间之后没有足够大的空间 :

情况1当是情况1 的时候,要扩展内存就直接原有内存之后直接追加空间,原来空间的数据不发生变化。情况2当是情况2 的时候,原有空间之后没有足够多的空间时,扩展的方法是:在堆空间上另找一个合适大小的连续空间来使用。这样函数返回的是一个新的内存地址。由于上述的两种情况,realloc函数的使用就要注意一些
边栏推荐
猜你喜欢

组件中的自定义事件

XSSGAME小游戏(XSS学习)level1-15

Mysql的索引为什么用的是B+树?

Switch exchanges

Visual studio 2022 interesting and powerful intelligent auxiliary coding

理解ASP.NET Core - 基于Cookie的身份认证(Authentication)

部署metersphere
![[unity daily bug] unity reports an unexpected character '‘](/img/e8/11eec670112a5a7e4f1e71dc93c1c0.png)
[unity daily bug] unity reports an unexpected character '‘

04_ UE4 advanced_ Introduction to physical collision and firing fireballs

Error in na.fail.default(list(Purchase = c(“CH“, “CH“, “CH“, “MM“, “CH“, : missing values in obj
随机推荐
0 basic career change software test, the necessary skills with a monthly salary of 6000 and 11000 are quite different
Visual studio 2022 interesting and powerful intelligent auxiliary coding
微信小程序封装wx.request
PMP每日一练 | 考试不迷路-7.22
Switch exchanges
Niuke brush questions - Sword finger offer (phase II)
SQLZOO——SELECT Quiz
资源池以及资源池化是什么意思?
云徙科技CTO李楠:技术和技术人,与数字化共同进化
Li Nan, CTO of Yunqian Technology: technology and technical people, coevolution with digitalization
PyQt5_ Qlistwidget paging multiple selection control
JMeter record the BeanShell written into excel instance caused by an automatic data generation
C ivalueconverter interface usage example
Exciting metauniverse! Wealth outlet of next generation Internet
Important knowledge of application layer (interview, reexamination, term end)
美团8年经验之谈,测试工程师如何进阶(自动化、性能、测开)
04_ue4进阶_物理碰撞入门和发射火球
Redis源码与设计剖析 -- 7.快速列表
Global event bus
C# IValueConverter接口用法举例
