当前位置:网站首页>C陷阱与缺陷 第7章 可移植性缺陷 7.10 首先释放,然后重新分配
C陷阱与缺陷 第7章 可移植性缺陷 7.10 首先释放,然后重新分配
2022-08-01 21:00:00 【weixin_客子光阴】
首先释放,然后重新分配
C语言实现都为使用人员提供了3个内存分配函数:malloc、realloc和free。malloc(n)将返回一个指针,指向一块新分配的可以容纳n的字符的内存,编程人员可以使用这块内存。free将释放malloc分配的内存,方式是通过把malloc函数返回的指针作为参数传递给free函数。realloc需要把指向一块内存已分配内存的区域指针以及这块内存新的大小作为参数传入,就可以调整(扩大或缩小)这块内存区域为新的大小,这个过程中有可能涉及内存的复制。
内存重分配(reallocation)
这一实现允许某内存块被释放之后重新分配其大小,前提是内存重分配(reallocation)操作执行得必须足够早。(UNIX)
例如,下面的代码就是合法的:
free(p);
p = realloc(p, newsize);
释放一个链表中的所有元素:
for (p = head; p != NULL; p = p->next) {
free((char *)p)
}
这里,我们不必担心调用free之后,会使p->next变得无效当着,这种技巧不值得推荐。(有可能在其它系统上失败)
边栏推荐
- 【Kaggle】Classify Leaves
- 漏洞分析丨HEVD-0x6.UninitializedStackVariable[win7x86]
- 使用员工管理软件,解锁人力生产力新水平,提高人力资源团队灵活性
- 15 分钟带你入门 Grafana
- 列表页常见的 hook 封装
- tiup mirror init
- LeetCode每日一题(1807. Evaluate the Bracket Pairs of a String)
- 网络安全与基础设施安全局(CISA):两国将在网络安全方面扩大合作
- 【微信小程序】【AR】threejs-miniprogram 安装(76/100)
- Buttons with good user experience should not have hover state on mobile phones
猜你喜欢
随机推荐
[Personal work] Wireless network image transmission module
响应式织梦模板美容整形类网站
[Energy Conservation Institute] Ankerui Food and Beverage Fume Monitoring Cloud Platform Helps Fight Air Pollution
Interview assault 70: what is the glue bag and a bag?How to solve?
MySQL Syntax Basics
R语言 数据的关系探索
【Untitled】
系统收集集
Simple test of the use of iptables
vant实现Select效果--单选和多选
Goroutine Leaks - The Forgotten Sender
Multithreaded producers and consumers
和我一起写一个音乐播放器,听一首最伟大的作品
C专家编程 第1章 C:穿越时空的迷雾 1.1 C语言的史前阶段
乐观锁批量跟新 纯SQL
Use WeChat official account to send information to designated WeChat users
技能大赛训练:A部分加固题目
To promote energy conservation institute 】 【 the opinions of the agricultural water price reform
Convolutional Neural Network (CNN) mnist Digit Recognition - Tensorflow
OSG Notes: Set DO_NOT_COMPUTE_NEAR_FAR to manually calculate far and near planes








