26

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.

razlebe
  • 7,134
  • 6
  • 42
  • 57
Bali C
  • 30,582
  • 35
  • 123
  • 152
  • 15
    It is very feasible in C#. A common cause is people that believe it is not feasible and don't worry about it. – R. Martinho Fernandes Aug 30 '11 at 11:40
  • 3
    Haha! Born to be wild! :) The not so practical answer would be: just write a moderately sized C++ program and it'll have memory leaks :) (just jocking) – Diego Sevilla Aug 30 '11 at 11:40
  • 1
    What's a "system memory leak", as opposed to any other kind of memory leak? Do you mean that you want to create a leak that persists beyond the lifetime of the program? That can happen if (and only if) some implementation-defined API lets you do something that consumes kernel resources indefinitely. For example you could start a daemon process or similar. Even that's not strictly "leaked", since it's still accessible via the process list and could be killed later. – Steve Jessop Aug 30 '11 at 11:53
  • @Steve I just meant a memory leak in general really, someone edited to a better question title already – Bali C Aug 30 '11 at 11:58

10 Answers10

31

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
}
StackedCrooked
  • 34,653
  • 44
  • 154
  • 278
  • So presumably that would leak memory once as the new int is still in memory, if that were in an infinite for loop then it would leak until the program has been killed? – Bali C Aug 30 '11 at 11:48
  • 3
    If it were an infinite loop then it would leak an "infinite" amount of memory (until the system hangs or forcibly kills the process). – StackedCrooked Aug 30 '11 at 11:50
  • @StackedCrooked So is this the only way a memory leak can happen in C++. (Sorry I am a C++ beginner). – Supertecnoboff Apr 20 '14 at 16:15
  • 1
    @Supertecnoboff There are many ways in which memory leaks can happen. Just keep learning :) – StackedCrooked Feb 10 '19 at 17:42
27
  1. Create pointer to object and allocate it on the heap
  2. Don't delete it.
  3. Repeat previous steps
  4. ????
  5. PROFIT
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
  • 2
    creating a pointer isn't enough. It has to point to a heap-allocated object (and even then, the pointer isn't really important) – jalf Aug 30 '11 at 11:41
16
int main() {
    while(true) new int;
}
Puppy
  • 144,682
  • 38
  • 256
  • 465
  • Ah, true enough. I was focused on C#; The OP's requirement to have it in C++ is not really necessary. But, it's ok to answer in C++, of course – sehe Aug 30 '11 at 11:43
  • why not simply while(new int); ? – Luchian Grigore Aug 30 '11 at 11:44
  • 3
    @Luchian: A pointer allocation as boolean condition? That's not simple or clear at all. – Puppy Aug 30 '11 at 11:46
  • 5
    @sehe: The question is how to create a leak in C++- why the hell would anyone answer in C#? – Puppy Aug 30 '11 at 11:47
  • @DeadMG: Because it sucks to do it in C++ only because it is believed to be impossible in C#? _`I am aware that it is not really feasible to do it in C# as it is managed code`_ is just false information. – sehe Aug 30 '11 at 11:49
  • To leak memory even quicker, replace `new int` with `new char[N]`, where `N` controls how quickly you leak memory. – Martin B Aug 30 '11 at 11:51
  • @sehe: True. But that's still not actually the question. – Puppy Aug 30 '11 at 11:51
  • 2
    @DeadMG are we supposed to be clear in designing our memory leaks? :D Also, it is simple... new int returns a pointer which can be evaluated to a boolean... – Luchian Grigore Aug 30 '11 at 11:52
  • @DeadMG: no offense, I said it's ok to answer in C++! My comment was wrong, way too quick and ... deleted – sehe Aug 30 '11 at 11:53
  • @Luchian: If you design something in, it should be clear. And it's not simple because that's not exactly a normal use of `new`. – Puppy Aug 30 '11 at 12:12
  • IT CRASHED MY COMPUTER! Rebooted and everything's fine. That was amazing. – Defacto Jul 04 '19 at 07:50
8

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.

David Hammen
  • 32,454
  • 9
  • 60
  • 108
3
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

somenath mukhopadhyay
  • 1,548
  • 1
  • 16
  • 18
3

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.

Patrick B.
  • 11,773
  • 8
  • 58
  • 101
2

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.

Abdel Aleem
  • 667
  • 10
  • 15
2

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

sehe
  • 374,641
  • 47
  • 450
  • 633
1

It's as simple as:⠀⠀⠀

new int;
Sapphire_Brick
  • 1,560
  • 12
  • 26
0
#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

Omar Osama
  • 1,401
  • 3
  • 19
  • 29
  • 1
    Does this mean the memory is reduced? I mean does memory allocated to app and not returned to OS never be available to be used by other apps? – Mahdi-Malv Dec 07 '18 at 19:19