是否免费(PTR)其中PTR为NULL损坏内存? [英] Does free(ptr) where ptr is NULL corrupt memory?
问题描述
理论上我可以说,
免费(PTR);
免费(PTR);
是一个内存破坏,因为我们释放已经被释放的内存。
但是,如果
免费(PTR);
PTR = NULL;
免费(PTR);
由于操作系统将在不确定的方式表现我不能让这发生的事情一个实际的理论分析。
不管我做的,这是内存损坏或不?
时释放一个NULL指针是否有效?
7.20.3.2的
免费
函数
简介
的#include<&stdlib.h中GT;
无效免费(无效* PTR);
说明
的
免费
功能使空间指向PTR
被释放,也就是说,国产
可用于进一步分配。如果PTR
是一个空指针时,没有采取行动。
块引用>请参阅 ISO-IEC 9899 。
话虽这么说,看着野生不同codebases的时候,你会发现人们有时会做的事:
如果(PTR)
免费(PTR);这是因为有些C运行库(我肯定记得那是在PalmOS的情况下)释放一个
NULL
指针时就会崩溃。但现在,我相信它是安全的假设
免费(NULL)
是一个NOP按照该标准的指导。Theoretically I can say that
free(ptr); free(ptr);
is a memory corruption since we are freeing the memory which has already been freed.
But what if
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?
Is freeing a NULL pointer valid?
解决方案7.20.3.2 The
free
functionSynopsis
#include <stdlib.h> void free(void *ptr);
Description
The
free
function causes the space pointed to byptr
to be deallocated, that is, made available for further allocation. Ifptr
is a null pointer, no action occurs.See ISO-IEC 9899.
That being said, when looking at different codebases in the wild, you'll notice people sometimes do:
if (ptr) free(ptr);
This is because some C runtimes (I for sure remember it was the case on PalmOS) would crash when freeing a
NULL
pointer.But nowadays, I believe it's safe to assume
free(NULL)
is a nop as per instructed by the standard.这篇关于是否免费(PTR)其中PTR为NULL损坏内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!