C++ program using more memory than available on the system?

Viewed 209

I've written the following memory hogging program:

int main() {
    while(1) {
        auto* blah = new char[1024 * 1024 * 1024]{};
    }
    return 0;
}

Which, as far I can tell, reserves a whole GB of memory on every iteration on the loop. I was expecting this to crash almost immediately. But it somehow runs until I stop it. Inspecting my system I discovered that my little program is taking up more memory than available on my machine, how is this possible? what's going on here?

enter image description here

2 Answers

Modern operating systems can be clever about memory allocation and not actually allocate anything until you use the memory you tried to allocate. On such systems malloc and new don't fail when you allocate, but the whole program goes down when you try to use the memory OS told you it allocated even though it physically can't. See this for more on that.

Add blah[1024 * 1024 * 1024 - 1] = 127; after line with new. Probably there is optimisation for unused block of memory. Have you tried to see (printf) the addresses allocated for blah?

Related