内存泄漏、访问释放的内存和双重释放有什么区别? [英] What is the difference between memory leak, accessing freed memory and double free?

查看:145
本文介绍了内存泄漏、访问释放的内存和双重释放有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出与内存模型相关的这三种问题之间的区别.

I'm trying to figure out what is the difference between those three kinds of problems associated with memory models.

如果我想模拟一个内存泄漏场景,我可以创建一个指针,而无需调用相应的删除方法.

If I want to simulate a memory leak scenario, I can create a pointer without calling corresponding delete method.

int main() {
    // OK
    int * p = new int;
    delete p; 

    // Memory leak
    int * q = new int;
    // no delete
}

如果我想模拟一个double free场景,我可以释放一个指针两次,这部分内存将在以后分配两次.

If I want to simulate a double free scenario, I can free a pointer twice and this part memory will be assigned twice later.

a = malloc(10);     // 0xa04010
b = malloc(10);     // 0xa04030
c = malloc(10);     // 0xa04050

free(a);
free(b);  // To bypass "double free or corruption (fasttop)" check
free(a);  // Double Free !!

d = malloc(10);     // 0xa04010
e = malloc(10);     // 0xa04030
f = malloc(10);     // 0xa04010   - Same as 'd' !

然而,我不知道什么是访问释放的内存.谁能给我一个访问释放内存的例子?

However, I don't know what is accessing freed memory. Can anybody give me an example of accessing freed memory?

推荐答案

  1. 内存泄漏很糟糕.
  2. 双免费更糟.
  3. 访问释放的内存更糟.

内存泄漏

这不是一个错误本身.泄漏的程序仍然有效.这可能不是问题.但这仍然很糟糕;随着时间的推移,您的程序将从主机保留内存并且永远不会释放它.如果在程序完成之前主机的内存已满,您就会遇到麻烦.

Memory leaks

This is not an error per se. A leaking program is stil valid. It may not be a problem. But this is still bad; with time, your program will reserve memory from the host and never release it. If the host's memory is full before the program completion, you run into troubles.

根据标准,这是未定义的行为.实际上,这几乎总是由 C++ 运行时调用 std::abort().

Per the standard, this is undefined behaviour. In practice, this is almost always a call to std::abort() by the C++ runtime.

还有未定义的行为.但在某些情况下,不会有什么不好的事情发生.您将测试您的程序,并将其投入生产.总有一天,它会无缘无故地崩溃.它会硬断:随机.修改简历的最佳时机.

Also undefined behaviour. But in some case, nothing bad will happen. You'll test your program, put it in production. And some day, for no apparent reason, it will break. And it will break hard: randomly. The best time to rework your résumé.

这里是如何访问释放的内存:

And here is how to access freed memory:

// dont do this at home
int* n = new int{};
delete n;
std::cout << *n << "\n"; // UNDEFINED BEHAVIOUR. DONT.

这篇关于内存泄漏、访问释放的内存和双重释放有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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