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.

1
2
3
4
5
6
7
8
9
10
11
#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!
pp = new int[1000000];
it is unlikely to crash your system. most os are smart enough to not let you do that. It may slow down, though. even the above is going to take a bit to drain a new computer, feel free to add more zeros.
Last edited on
Thank you for help @jonnin! I just needed it to go over at least 1GB of memory leak. My os was using 3.5 GB (normal performance) and it went over to 5.5 GB with the program running.
Your program is crashing, but you are not creating a memory leak. new is throwing an exception for trying to allocate more memory than you have available.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <exception>

int main()
{
   std::cout << "Enter number of integers you wish to reserve: ";
   long Input { };
   std::cin >> Input;

   try
   {
      // request memory space and then return it
      long* pReservedInts = new long[Input];
      delete[] pReservedInts;
   }

   catch (std::bad_alloc& exp)
   {
      std::cout << "Exception caught: " << exp.what() << ".\n";
   }

   catch (...)
   {
      std::cout << "Generic exception caught.\n";
   }

   std::cout << "Continuing on our merry way\n";
}

Enter number of integers you wish to reserve: 999999999
Exception caught: bad allocation.
Continuing on our merry way
Last edited on
Topic archived. No new replies allowed.