释放内存的两倍 [英] Freeing memory twice

查看:129
本文介绍了释放内存的两倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C和C ++,释放空指针会导致一事无成。

不过,我看到人们说,内存损坏可能发生,如果你的自由内存的两倍。

这是真的吗?什么是引擎盖下怎么回事,当你释放内存两次?


解决方案

 为int * p =的malloc(sizeof的(INT));
//的P值现在可以说为0x12345678* p值= 2;
自由(对); //内存指针被释放,但依然是P的值是为0x12345678
         //现在,如果你再免费,你会得到一个崩溃或不确​​定的行为。

于是,经过免费 ING的第一次,你应该做的 P = NULL ,因此,如果(通过任何机会),免费(p)再次调用,什么也不会发生。

这是为什么释放内存的两倍未定义:为什么免费崩溃时调用两次

In C and C++, Freeing a NULL pointer will result in nothing done.

Still, I see people saying that memory corruption can occur if you "free memory twice".

Is this true? What is going on under the hood when you free memory twice?

解决方案

int *p = malloc(sizeof(int));
//value of p is now lets say 0x12345678

*p = 2;
free(p); //memory pointer is freed, but still value of p is 0x12345678
         //now, if you free again, you get a crash or undefined behavior.

So, after free ing the first time, you should do p = NULL , so if (by any chance), free(p) is called again, nothing will happen.

Here is why freeing memory twice is undefined: Why Free crashes when called twice

这篇关于释放内存的两倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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