简体   繁体   中英

How to (deliberately) cause a program crash in C++ using new

I'm trying to get the hang of C++ memory management and try to deliberately crash my program using an infinite loop of new statements. As I understand, this just reserves more and more space on the heap of the memory. However my program just won't crash. Monitoring it in the Windows task manager, it will go to about ~6GB of memory usage, but then drop down to 5GB, go up to 6GB again, etc.

Meanwhile my hard drive is quickly filling up. I stopped the test after the allocation of about 30GB because I didn't want to cause too much stress on my SSD.

Now, I have 8GB of RAM and according to Windows settings, the "virtual memory size" (I guess it's the swap, right?) is about ~1.5GB. However I was able to allocate much more than that. What determines whether the program will finally crash? What memory did it use?

Thanks!

#include <iostream>
using namespace std;

int main() {
    long alloced = 0;
    while (true) {
        double *d = new double[12500000]; 
        alloced += 1;
        cout << alloced << " times 100MB" << endl;
    }
    return 0;
}

Now, I have 8GB of RAM and according to Windows settings, the "virtual memory size" (I guess it's the swap, right?) is about ~1.5GB.

This is a common confusion. Windows happens to implement swap through its virtual memory system, and this happens to be the only configurable setting in Windows virtual memory system. This has led a lot of people to think that swapping is the same as virtual memory.

This is incorrect. Swapping was invented before virtual memory even existed, and there are many systems with virtual memory that have no swapping at all (most home WiFi routers). They're completely different things.

The 1.5GB you're talking about is the size of your page file.

However I was able to allocate much more than that. What determines whether the program will finally crash? What memory did it use?

It used virtual memory, which a 64-bit operating system can create in the terabytes. It's not a scarce resource.

To get your program to crash, you need to use memory, not just allocate it. Some operating systems do allow you to impose a virtual memory limit on processes, though I'm not sure if Windows is one of them. (This is not a good idea in general.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM