I thought this might be a helpful class for C++ programmers:
Example:
// Allocate memory, overwrite beyond the bounds of the memory
// allocated. We want to corrupt the heap here..
char *s = new char[100];
memset(s,0,120);
// Test to see if the heap is corrupted:
Heap heap;
bool heapIsOk = heap.ValidateAllHeaps();
...
Heap.h
class Heap
{
private:
unsigned long getCombinedSizesOfProcessHeaps(void);
public:
Heap();
virtual ~Heap();
bool ValidateAllHeaps(void);
bool ValidateHeap(HANDLE heap);
unsigned long GetCombinedSizesOfProcessHeaps(void);
unsigned long GetHeapSize(HANDLE heap);
};
Heap.cpp
#include <windows.h>
#include <stdio.h>
#include "Heap.h"
unsigned long Heap::GetCombinedSizesOfProcessHeaps(void)
{
return getCombinedSizesOfProcessHeaps();
}
bool Heap::ValidateAllHeaps(void)
{
HANDLE hHeaps[250];
DWORD numHeaps = GetProcessHeaps(250,hHeaps);
unsigned long i;
if (numHeaps <= 250)
{
for (i=0; i<numHeaps; i++)
{
if (!ValidateHeap(hHeaps[i]))
{
return false;
}
}
}
else
{
// Too many heaps!
return false;
}
return true;
}
bool Heap::ValidateHeap(HANDLE heap)
{
if (HeapValidate(heap,0,0) == 0)
{
return false;
}
else
{
return true;
}
}
unsigned long Heap::getCombinedSizesOfProcessHeaps(void)
{
HANDLE hHeaps[250];
unsigned long sz = 0;
DWORD numHeaps = GetProcessHeaps(250,hHeaps);
unsigned long i;
if (numHeaps <= 250)
{
for (i=0; i<numHeaps; i++)
{
sz += GetHeapSize(hHeaps[i]);
}
}
else
{
// Too many heaps!
return 0;
}
return sz;
}
unsigned long Heap::GetHeapSize(HANDLE heap)
{
unsigned long sz = 0;
HeapLock(heap);
PROCESS_HEAP_ENTRY entry;
memset(&entry,'\0',sizeof entry);
while (HeapWalk(heap,&entry))
{
if (entry.wFlags == PROCESS_HEAP_ENTRY_BUSY)
{
sz += entry.cbData;
}
}
HeapUnlock(heap);
return sz;
}
Heap::Heap()
{
}
Heap::~Heap()
{
}