如何在 C++ 中创建内存泄漏?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7242493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:40:24  来源:igfitidea点击:

How to create a memory leak in C++?

c++memory-leaks

提问by Bali C

I was just wondering how you could create a system memory leak using C++. I have done some googling on this but not much came up, I am aware that it is not really feasible to do it in C# as it is managed code but wondered if there was a simple way to do this with C++? I just thought it would be interesting to see how much the system suffers because of code not being written properly. Thanks.

我只是想知道如何使用 C++ 创建系统内存泄漏。我已经对此进行了一些谷歌搜索,但没有太多发现,我知道在 C# 中这样做并不可行,因为它是托管代码,但想知道是否有一种简单的方法可以用 C++ 做到这一点?我只是觉得看看系统因代码编写不当而遭受的损失会很有趣。谢谢。

回答by StackedCrooked

A memory leak occurs when you call newwithout calling a corresponding deletelater. As illustrated in this sample code:

当您调用后new未调用相应的函数时,就会发生内存泄漏delete。如本示例代码所示:

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

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

回答by Tony The Lion

  1. Create pointer to object and allocate it on the heap
  2. Don't delete it.
  3. Repeat previous steps
  4. ????
  5. PROFIT
  1. 创建指向对象的指针并在堆上分配它
  2. 不要删除它。
  3. 重复前面的步骤
  4. ???
  5. 利润

回答by Puppy

int main() {
    while(true) new int;
}

回答by David Hammen

There are many kinds of memory leaks:

内存泄漏有很多种:

  • Allocated memory that is unreleasable because nothing points to it.
    These kind of leaks are easy to create in C and C++. They are also pretty easy to prevent, easy to detect, and easy to cure. Because they are easy to detect there are lots of tools, free and commercial, to help find such leaks.

  • Still-accessible allocated memory that should have been released a long time ago.
    These kinds of leaks are much harder to detect, prevent, or cure. Something still points to it, and it will be released eventually-- for example, right before exit(). Technically speaking, this isn't quite a leak, but for all practical purposes it is a leak. Lots of supposedly leak-free applications have such leaks. All you have to do is run a system profile to see some silly application consume ever more memory. These kinds of leaks are easy to create even in managed languages.

  • Allocated memory that should never have been allocated in the first place.
    Example: A user can easily ask Matlab to creating these kinds of leaks. Matlab is also rather aggressive at creating these kinds of leaks. When Matlab gets a failure from mallocit goes into a loop where it waits for a bit and then retries the malloc. Meanwhile, the OS frantically tries to deal with the loss of memory by shuffling chunks of programs from real memory into virtual memory. Eventually everything is in virtual memory -- and everything creeps to a standstill.

  • 无法释放的已分配内存,因为没有任何内容指向它。
    这种泄漏很容易在 C 和 C++ 中创建。它们也很容易预防、检测和治愈。因为它们很容易检测,所以有很多免费和商业工具可以帮助找到此类泄漏。

  • 很久以前就应该释放的仍可访问的已分配内存。
    这些类型的泄漏更难检测、预防或治愈。有些东西仍然指向它,它最终会被释放——例如,就在exit(). 从技术上讲,这算不上泄漏,但就所有实际目的而言,这都是泄漏。许多据称无泄漏的应用程序都有这样的泄漏。您所要做的就是运行系统配置文件以查看一些愚蠢的应用程序消耗更多内存。即使在托管语言中,这些类型的泄漏也很容易创建。

  • 本来就不应该分配的已分配内存。
    示例:用户可以轻松地要求 Matlab 创建这些类型的泄漏。Matlab 在创建这些类型的泄漏方面也相当积极。当 Matlab 出现故障时,malloc它会进入一个循环,等待一段时间,然后重试malloc. 同时,操作系统疯狂地尝试通过将大量程序从真实内存改组到虚拟内存来处理内存丢失。最终一切都在虚拟内存中——一切都变得停滞不前。

回答by Patrick B.

Just write an application which allocates "a lot of data" and then blocks until it is killed. Just run this program and leave it running.

只需编写一个分配“大量数据”的应用程序,然后阻塞直到它被杀死。只需运行这个程序并让它继续运行。

回答by sehe

In C#, just use P/Invoke to allocate a lot of memory, resource handles and keep them around.

在 C# 中,只需使用 P/Invoke 分配大量内存、资源句柄并保留它们。

You can use unmanaged code just fine in a simple C# harness

您可以在简单的 C# 工具中很好地使用非托管代码

回答by somenath mukhopadhyay

class ClassWithLeakedMemory{
private:
    char* str;
public:
    ClassWithLeakedMemory(){
        str = new char[100];
    }

    ~ClassWithLeakedMemory(){
        cout<<"We are not freeing the dynamically allocated string memory"<<endl;
    }

};


class ClassWithNoLeakedMemory{
private:
    char* str;
public:
    ClassWithNoLeakedMemory(){
        str = new char[100];
    }

    ~ClassWithNoLeakedMemory(){
        cout<<"We are freeing the dynamically allocated string memory"<<endl;
        delete[] str;
        str = null;

    }

};

int main() {
    //we are creating an automatic object of the ClassWithleakedMemory
    //when we will come out of the main, this object will be
    //out of scope. hence it will be deleted. so destructor will
    //be called. but in the destructor, we have not specifically
    //deleted the dynamically allocated string.

    //so the stack based pointer object str will be deleted but the   memory  
    //it was pointing to won't be deleted. so we will be left with an
    //unreferenced memory. that is memory leak.
    ClassWithLeakedMemory objectWithLeakedmemory;
    ClassWithNoLeakedMemory objectWithNoLeakedmemory;
    return 0;
}

The way the stack based pointer object refers to the dynamically allocated memory in both the classes can be shown pictorially as below:

基于堆栈的指针对象引用两个类中动态分配的内存的方式可以如下图所示:

enter image description here

在此处输入图片说明

回答by Abdel Aleem

When an object that is created using newis no longer referenced, the deleteoperator has to be applied to it. If not, the memory it occupies will be lost until the program terminates. This is known as a memory leak. Here is an illustration:

new不再引用使用创建的对象时,delete必须对其应用运算符。如果没有,它占用的内存将丢失,直到程序终止。这称为内存泄漏。这是一个插图:

#include <vector>
using namespace std;

void memory_leak(int nbr)
{
   vector<int> *ptrVector = new vector<int>(nbr);
   // some other stuff ...
   return;
}

If we return without calling deleteon the object (i.e. delete ptrToVector) a memory leak occurs. To avoid this, don't allocate the local object on the memory heap but instead use a stack-allocated variable because these get automatically cleaned up when the functions exits. To allocate the vector on the run-time stack avoid using new(which creates it on the heap) and the pointer.

如果我们在没有调用delete对象的情况下返回(即delete ptrToVector),则会发生内存泄漏。为了避免这种情况,不要在内存堆上分配本地对象,而是使用堆栈分配的变量,因为这些变量会在函数退出时自动清除。要在运行时堆栈上分配向量,请避免使用new(在堆上创建它)和指针。

回答by Sapphire_Brick

This statement always produces a memory leak:

此语句总是会产生内存泄漏:

new int;

回答by Omar Osama

#include <stdio.h>

void main(){

for(int i = 0; i < 1000; i++)

double* ptr = (double*)malloc(1000000*sizeof(double))

//free(ptr);

ptr = NULL;

}

note : the hashed line of code caused a memory leak while the process allocated it and did't return it back to the OS

注意:散列代码行导致内存泄漏,同时进程分配它并且没有将它返回给操作系统