From: Ulrich Eckhardt on
Greetings!

For all that want to see how their code behaves when it runs out of memory,
here's a small piece of code:

// available memory, 16MiB in this case
SIZE_T const reserve_size = 16*1024*1024;
// reserve available memory
LPVOID reserve = VirtualAlloc( 0, reserve_size,
MEM_RESERVE, PAGE_READWRITE);
assert(reserve);
// exhaust virtual address space by reserving more and more of it
while(1) {
// 1MiB granularity
SIZE_T const granularity = 1*1024*1024;
LPVOID p = VirtualAlloc( 0, granularity,
MEM_RESERVE, PAGE_READWRITE);
if(!p)
break;
}
// release reserved memory again
if(!VirtualFree( reserve, 0, MEM_RELEASE))
assert(false);


What it does is to simply reserve all the virtual addres space except a
certain amount (16MiB here). The advantage to using malloc() is that it
doesn't cause excessive swapping and the ensuing slowdown. Just put this
code at the beginning of main() or a similar place and watch how your code
behaves when malloc() or new start failing. Note: new throws bad_alloc on
failure, but MSVC is notorious at getting this very simple thing wrong.

Questions? Comments? Suggestions?

BTW: I'd be interested how much address space you can reserve on a 64 bit
system, so if anyone has one could they run this?

Uli

--
C++ FAQ: http://parashift.com/c++-faq-lite

Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
From: Carl Daniel [VC++ MVP] on
Ulrich Eckhardt wrote:
> Greetings!
>
> For all that want to see how their code behaves when it runs out of
> memory, here's a small piece of code:

[code snipped]

>
> Questions? Comments? Suggestions?

Nice!

operator new throws by default on VC++ 7.1 or later, but there's always an
option to return to the pre-standard behavior of returning null.

It would be interesting to try a couple more block sizes after exhausting
the 1MB blocks - maybe 64K and then 4K to really make sure that the
available space is the 16MB reserved and nothing more.

>
> BTW: I'd be interested how much address space you can reserve on a 64
> bit system, so if anyone has one could they run this?

I might be able to give it a try later today - I'll post back my results if
so.

-cd