free(ptr) where ptr is NULL 是否会损坏内存? [英] Does free(ptr) where ptr is NULL corrupt memory?

查看:25
本文介绍了free(ptr) where ptr is NULL 是否会损坏内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

理论上我可以这么说

free(ptr);
free(ptr); 

是内存损坏,因为我们正在释放已经释放的内存.

is a memory corruption since we are freeing the memory which has already been freed.

但是如果

free(ptr);
ptr=NULL;
free(ptr); 

由于操作系统将以未定义的方式运行,因此我无法对此进行实际的理论分析.无论我在做什么,这是否是内存损坏?

As the OS will behave in an undefined manner I cannot get an actual theoretical analysis for this about what's happening. Whatever I am doing, is this memory corruption or not?

释放空指针是否有效?

推荐答案

7.20.3.2 free 函数

简介

#include <stdlib.h> 
void free(void *ptr); 

说明

free 函数使ptr 指向的空间被释放,即可供进一步分配.如果 ptr 是空指针,则不会发生任何动作.

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.

请参阅ISO-IEC 9899.

话虽如此,在野外查看不同的代码库时,您会注意到人们有时会这样做:

That being said, when looking at different codebases in the wild, you'll notice people sometimes do:

if (ptr)
  free(ptr);

这是因为一些 C 运行时(我肯定记得在 PalmOS 上就是这种情况)在释放 NULL 指针时会崩溃.

This is because some C runtimes (I for sure remember it was the case on PalmOS) would crash when freeing a NULL pointer.

但是现在,我相信可以安全地假设 free(NULL) 按照标准的指示是一个 nop.

But nowadays, I believe it's safe to assume free(NULL) is a nop as per instructed by the standard.

这篇关于free(ptr) where ptr is NULL 是否会损坏内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆