是否免费(PTR)其中PTR为NULL损坏内存? [英] Does free(ptr) where ptr is NULL corrupt memory?

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

问题描述

理论上我可以说,

 免费(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 function

Synopsis

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

Description

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.

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屋!

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