Zip Component, Email Component, Encryption Component ActiveX Control for Zip Compression .NET Components for ASP.NET
ActiveX and .NET Components for Zip Compression, Encryption, Email, XML, S/MIME, HTML Email, Character Encoding, Digital Certificates, FTP, and more ASP Email ActiveX Component


Index of Chilkat Blog Posts

February 5, 2008

C++ Source to Validate Heaps and Calculate Heap Size

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()
{
	
}


Privacy Statement. Copyright 2000-2011 Chilkat Software, Inc. All rights reserved.
Send feedback to support@chilkatsoft.com

Components for Microsoft Windows XP, 2000, 2003 Server, Vista, Windows 7, and Windows 95/98/NT4.