Orion98
Orion98

Reputation: 91

Creating a memory leak with C++

I've been trying to create a program that causes memory leak where it will crash my system.

The code below managed to cause a small spike of memory leak in my task manager.

#include <iostream>
using namespace std;

int main()
{
    while(true)new int;
    int * pp = nullptr;
    pp = new int;

    return 0;
}

If anyone could help me out on how to improve the memory leak, I would appreciate it!

Upvotes: 2

Views: 438

Answers (1)

eerorika
eerorika

Reputation: 238301

To "improve" the memory leak.

  • Allocate a bigger object, such as an array of a many integers to consume space faster.
  • Touch the allocated memory (by modifying it) to force the operating system to commit memory to the process. This might not be necessary if you configure the operating system to not overcommit memory.
  • Make sure that the modification has observable effects so that optimiser doesn't remove it (calculate a sum or something).
  • Don't have an infinite loop that doesn't call any library I/O function, nor performs an access through a volatile glvalue, nor perform a synchronization operation nor an atomic operation. There's a language rule that allows the implementation to assume that one of those happens, and if your loop is guaranteed to not do them, then it might not happen at all because behaviour is undefined... Maybe new int within the loop is sufficient, since it is potentially throwing, and thus the loop may not be proven to be infinite, but I'm not certain.

The operating system should hopefully choose to kill your program when memory runs out.

Upvotes: 4

Related Questions