当前位置:网站首页>C语言动态内存函数的应用
C语言动态内存函数的应用
2022-06-22 00:35:00 【51CTO】
动态内存分配函数的应用
动态内存分配函数有:malloc,calloc,realloc和free,下列来说说它们的用法
1.malloc函数
malloc函数是用来向堆区申请指定字节大小的空间,函数参数为申请空间的字节大小,返回值为一个void*的指针,若申请失败会返回NULL,具体用法如下:
2.calloc函数
calloc函数和malloc函数相似,也是用来向堆区申请开辟内存空间并返回地址,calloc函数的第一个参数为申请空间中存储的元素个数,第二个参数为元素类型所占字节大小,函数返回值类型为void*,此外calloc函数会在开辟内存空间时并把空间的每个元素初始化为0,具体用法如下:
realloc函数
realloc函数是动态内存分配中非常重要的一个函数,它可以调整malloc和calloc所申请空间的大小,使其运用更加灵活,realloc函数的第一个参数为一个动态内存空间的指针,第二个参数为修改后的空间大小,返回值为修改后的空间地址,使用如下:
realloc函数注意事项:
1.如果p指向的空间之后有足够的内存可以追加可直接追加,后返回地址。
2.如果p指向的空间之后没有足够的内存空间可以追加,则realloc会重新找一块新的内存区域开辟一块满足需求的空间,并把原来内存中的数据拷贝回来,释放旧的内存空间,最后返回新开辟的内存空间地址。
3.要用一个新变量来接收realloc函数的返回值
4.free
free函数要与malloc/calloc函数成对使用,它是由来释放空间的,但释放后的指针并没有置为空指针依然有能力找到原本开辟的动态内存空间只会造成非法访问的问题,因此再用free释放空间后要把指针置为NULL。此外free释放的必须使动态开辟的内存空间,free空指针等于什么都没干。
边栏推荐
- English grammar_ Adverb - loud /aloud / loud
- Promise me not to use if (obj! = null) to judge empty
- yolov3 3D 语义点云paper阅读
- pm2 的学习
- isnull() ifnull() nullif()
- [Environmental stepping pit] pycharm reports an error when using QT
- HDOJ - Is It A Tree?
- Planification dynamique - 01 sac à dos, partitions et sous - ensembles, poids de la dernière pierre
- HDOJ - Is It A Tree?
- Want to join a big factory? Reading this article may help you
猜你喜欢

Pytorch learning 13: implement letnet and learning nn Module related basic operations

Pytorch learning 05: indexing and slicing

4G/wifi 能耗计量插座-监测电压电流功率

利用SSM框架实现用户登陆
![3 minutes, take you to play with chat robot automation [top template]](/img/71/4d848b46a52b71a351a086db248a95.png)
3 minutes, take you to play with chat robot automation [top template]

Want to join a big factory? Reading this article may help you

Compilation principle - recursive descent subroutine method

ShardingSphere-proxy-5.0.0分布式哈希取模分片实现(四)

Yolov3 3D semantic point cloud paper reading

Special survey of moving average strategy
随机推荐
PAT(甲) - 1001 A+B Format
03 FastJson 解决循环引用
Compilation principle - recursive descent subroutine method
FLowable运行时事务相关的表和表结构
The appearance, space, safety and power are all upgraded. The xinjietu x70s will be put on the market from 87900 yuan
Pytorch learning 02: handwritten digit recognition
IDEA提示 ‘Optional.get()‘ without ‘isPresent()‘ check错误。
52类110 个常用的组件和框架
【DailyFresh】课程记录
[redis] install redis in Ubuntu and the basic usage and configuration of redis
想加入大厂?看这篇文章也许会帮助到你
1876. 长度为三且各字符不同的子字符串
容器云是什么意思?与堡垒机有什么区别?
Special survey of moving average strategy
动态规划-01背包,分割等和子集,最后一块石头的重量
Judge whether the system CPU is idle
. Several methods of obtaining hinstance in. Net
使用 gomonkey Mock 函数及方法时遇到 panic: permission denied 的问题及解决方法
【环境踩坑】No module named ‘PyQt5‘
Virtual variables and formatting characters in debugging