How can I know the maximum size of the heap I can occupy by malloc()
. I use MS Visual Studio 2010?
There are operating system-dependent ways of finding out how much virtual memory is available for your process, but I do not know how to do this on windows. You can, however, find it out by doing a hunt+halving search, caling malloc with ever larger arguments until it fails, and then homing in on the value it balks at. Something like
for(i=1; v=malloc(i); i<<=1) free(v);
By this point you know that i/2 bytes is ok, while i bytes is not ok. Now do a bisection search for the actual maximum:
for(a=(i>>1), b=i; a < b-1;)
{
c=(a+b)>>1;
if(v=malloc(c)) { a=c; free(v); }
else b=c;
}
At this point, a
is the largest amount you can successfully allocate.