Following is my simple test. If you have a better test algorithm,
please drop me a line.
Thanks,
HJin
/*---------------------------------------------------------------------------
File name: HeapMemoryTest.cpp
Author: HJin
Created on: 6/21/2007 19:05:18
Modification history:
We want to know how big the heap memory is, when
we use new or malloc to dynamically allocate memory.
My machine has 1Gb physical memory, so the heap memory
is less than 1Gb. My test shows that 3/4 of the physical
memory can be used for the heap.
Sample output:
heap addr = 00385008
heap exhausted
heap addr ends at 2d20d728
approximate heap size is 718.533 M
Inside eat_memory(). heap addr is 00385008
Press any key to continue . . .
*/
#include <iostream>
#include <new>
using namespace std;
const int BlockSize = 1024; // 1k
int *pSave;
long addrKeeper = 0L;
bool hasMoreMemory = true;
void get_memory()
{
cerr << "heap exhausted" << endl;
cout<<"heap addr ends at "<<std::hex<<addrKeeper<<endl;
cout<<"approximate heap size is "<<std::oct<<double(addrKeeper-(long)pSave)/(1024.0*1024.0)<<" M"<<endl;
delete [] pSave; // release saved block
hasMoreMemory = false;
}
void eat_memory(int size)
{
/**
when this allocation fails, the system calls the new_handler.
Once the new_handler returns, hasMoreMemory = false.
*/
int *p = new int[size]; // allocate memory
if (hasMoreMemory)
{
addrKeeper = (long)p;
eat_memory(size); // recursive call
}
else
cerr << "Inside eat_memory(). heap addr is " << p << endl;
}
int main()
{
set_new_handler(get_memory); // specify handler
pSave = new int[BlockSize]; // save one block from heap
cerr << "heap addr = " << pSave << endl;
eat_memory(BlockSize);
return 0;
}