当前位置:网站首页>C pitfalls and pitfalls Chapter 7. Portability pitfalls 7.10 Free first, then realloc
C pitfalls and pitfalls Chapter 7. Portability pitfalls 7.10 Free first, then realloc
2022-08-01 21:04:00 【Weixin_ guest child time】
First release, then reallocate
The C language implementation provides three memory allocation functions for users: malloc, realloc and free.malloc(n) will return a pointer to a newly allocated block of memory that can hold characters of n, which the programmer can use.free will free the memory allocated by malloc by passing the pointer returned by the malloc function as an argument to the free function.realloc needs to pass in the pointer to the allocated memory area of a block of memory and the new size of the memory as parameters, so that the memory area can be adjusted (expanded or reduced) to the new size. This process may involve memory copying.
memory reallocation (reallocation)
This implementation allows a block of memory to be reallocated after it is freed, provided that the memory reallocation operation is performed early enough.(UNIX)
For example, the following code is legal:
free(p);
p = realloc(p, newsize);
Free all elements in a linked list:
for(p = head; p != NULL; p=p->next) {
free((char *)p)
}
Here, we don't have to worry about calling free, which will make p->next invalid.Recommended.(may fail on other systems)
边栏推荐
- Go Atomic
- STAHL touch screen repair all-in-one display screen ET-316-TX-TFT common faults
- C陷阱与缺陷 第7章 可移植性缺陷 7.7 除法运算时发生的截断
- PyTorch笔记 - Attention Is All You Need (2)
- 系统收集集
- ISC2022 HackingClub白帽峰会倒计时1天!最全议程正式公布!元宇宙集结,精彩绝伦!
- AQS原理和介绍
- 【Kaggle】Classify Leaves
- C专家编程 第1章 C:穿越时空的迷雾 1.5 今日之ANSI C
- Hiking, cured my mental internal friction
猜你喜欢
随机推荐
LeetCode每日一题(1807. Evaluate the Bracket Pairs of a String)
C专家编程 第1章 C:穿越时空的迷雾 1.4 K&R C
Pytorch学习记录(八):生成对抗网络GAN
R语言 pca主成分分析的主要方法
C陷阱与缺陷 第7章 可移植性缺陷 7.10 首先释放,然后重新分配
Goroutine Leaks - The Forgotten Sender
R语言 线性回归的有关方法
1374. 生成每种字符都是奇数个的字符串 : 简单构造模拟题
Pytorch框架学校记录11——搭建小实战完整细节
徒步,治好了我的精神内耗
【中文树库标记---CTB】
C陷阱与缺陷 第7章 可移植性缺陷 7.7 除法运算时发生的截断
idea插件generateAllSetMethod一键生成set/get方法以及bean对象转换
R语言 数据的关系探索
vant实现Select效果--单选和多选
PyTorch笔记 - Attention Is All You Need (2)
ISC2022 HackingClub white hat summit countdown 1 day!Most comprehensive agenda formally announced!Yuan universe, wonderful!
Classification interface, Taobao classification details API
封装一个管理 url 状态的 hook
string