How to create a memory leak in C++?

前端 未结 10 1302
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 00:35

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 t

相关标签:
10条回答
  • 2020-12-30 01:09

    It's as simple as:⠀⠀⠀

    new int;
    
    0 讨论(0)
  • 2020-12-30 01:15

    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.

    0 讨论(0)
  • 2020-12-30 01:17
    1. Create pointer to object and allocate it on the heap
    2. Don't delete it.
    3. Repeat previous steps
    4. ????
    5. PROFIT
    0 讨论(0)
  • 2020-12-30 01:19

    When an object that is created using new is no longer referenced, the delete operator 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:

    #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 delete on 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.

    0 讨论(0)
提交回复
热议问题