开发者

How to create a memory leak in 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 wondere开发者_如何学God 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.


A memory leak occurs when you call new without calling a corresponding delete later. As illustrated in this sample code:

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

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


  1. Create pointer to object and allocate it on the heap
  2. Don't delete it.
  3. Repeat previous steps
  4. ????
  5. PROFIT


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


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 malloc it 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.


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.


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:

How to create a memory leak in C++?


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

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


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.


It's as simple as:⠀⠀⠀

new int;


#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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜