当前位置:网站首页>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)
边栏推荐
猜你喜欢
随机推荐
JS Improvement: Handwritten Publish Subscriber Model (Xiaobai)
98.嵌入式控制器EC实战 EC开发板开发完成
C陷阱与缺陷 附录B Koenig和Moo夫妇访谈
【微信小程序】【AR】threejs-miniprogram 安装(76/100)
使用百度EasyDL实现厂区工人抽烟行为识别
WeChat applet cloud development | personal blog applet
任务调度线程池基本介绍
人工智能可信安全与评测
Pytorch框架学习记录8——最大池化的使用
JSD-2204-Knife4j框架-处理响应结果-Day07
Pytorch框架学习记录9——非线性激活
tiup mirror
Kubernetes 如何实现组件高可用
Imitation cattle forum project
网络安全与基础设施安全局(CISA):两国将在网络安全方面扩大合作
微服务负载均衡器Ribbon
Go Atomic
JS提升:手写发布订阅者模式(小白篇)
C陷阱与缺陷 第8章 建议与答案 8.1 建议
JS提升:如何中断Promise的链式调用