VS 2008, C++ std::bad_alloc at just 133 mb
I am running following code, trying to see how much max memory can i allocate
unsigned long* ptr;
for(unsigned long i=0; i<1000000000; i++) //1 billion
{
try
{
ptr = new unsigned long(0);
}
catch( bad_alloc &ba)
{
cout<<i;
}
}
I get bad_alloc exception at i=33401936, consider unsigned long takes 4 bytes, it is running out of memory at approx 133mb. However 32 bit address space should support up to 2GB. I have a 4GB ram so it should suffice and task manager says 2.5/4 GB is free.
I am using VS2008 on windows 7. Can anybody comment why is it failing at 133mb only.
Thanks,
Re: VS 2008, C++ std::bad_alloc at just 133 mb
Quote:
Originally Posted by
akshayd
I am running following code, trying to see how much max memory can i allocate
This does not test what you believe you're testing.
The only thing that the C++ "new" does is guarantee you have a pointer to the type, and therefore can be accessed safely. Nothing more, nothing less. The compiler could have gotten that memory from a memory pool, a big array allocated from the stack, or yes, from the OS. But you really know nothing about how much real memory was really allocated, or if any real memory was allocated at all.
For example, the compiler has the option of allocating more memory than you ask for. For example, extra bytes for guard bytes, for debugging purposes, or for the compiler's own internal heap memory management. So in other words, when you say "new T", at the end of the allocation, the total memory used for this request will more than likely be greater than sizeof(T).
If you really want to get a more realistic test, you have to use the OS specific heap allocation functions (for Windows you have HeapAlloc, etc.), and not "new", malloc(), or any such C++ heap-store/allocation functions.
Regards,
Paul McKenzie
Re: VS 2008, C++ std::bad_alloc at just 133 mb
You missed one fine point in your test (beside what Paul mentioned).
The first time through your loop, you allocate 4 bytes (but you never free that). The second time through you allocate 8 bytes (for a total of 12, but you never free that either).
This continues all the way through to your 33401936th iteration where you allocate about 133 MB - but the total you've allocated (without freeing it) is the sum of ALL of your individual allocations.
[Edit] My error - didn't read the original post (actually read it before the morning coffee!)
Re: VS 2008, C++ std::bad_alloc at just 133 mb