Click here to Skip to main content
15,896,063 members
Articles / Desktop Programming / MFC

Low Fragmentation Heap and Function Interception

Rate me:
Please Sign up or sign in to vote.
2.50/5 (8 votes)
14 Jan 20042 min read 41.7K   330   16  
How to implement a low fragmentation heap by intercepting HeapAlloc.
#include "stdafx.h"
#include "lfh.h"
#include "allocator.h"

LPLFHHEAP m_pHead = NULL;

bool SetLFH( HANDLE hHeap, bool bUseLFH )
{
	LPLFHHEAP pLFH = Find( hHeap );

	if(bUseLFH)
	{
		if(pLFH == NULL)
			Add( hHeap );
		else
			pLFH->bLFH = true;
	}
	else
	{
		if(pLFH != NULL)
			Delete (pLFH);
	}

	return true;
}

bool GetLFH ( HANDLE hHeap )
{
	LPLFHHEAP pHeap = Find( hHeap );

	if( pHeap == NULL)
		return false;

	return pHeap->bLFH;
}

LPLFHHEAP Find( HANDLE hHeap )
{
	LPLFHHEAP pCurrent = m_pHead;

	while(pCurrent != NULL)
	{
		if(pCurrent->hHeap == hHeap)
			return pCurrent;
		pCurrent = pCurrent->pNext;
	}
	return pCurrent;
}

void Add( HANDLE hHeap)
{
	LPLFHHEAP pNew	= new LFHHEAP;
	pNew->hHeap			= hHeap;
	pNew->pNext			= m_pHead;

	if(m_pHead != NULL)
		m_pHead->pPrev	= pNew;

	m_pHead					= pNew;
}

void Delete ( LPLFHHEAP pLFH )
{
	if(pLFH != NULL)
	{
		if(pLFH == m_pHead)
		{
			m_pHead = pLFH->pNext;
		}
		else
		{
			if(pLFH->pNext == NULL)			// Tail
			{
				pLFH->pPrev->pNext = NULL;
			}
			else
			{
				pLFH->pPrev->pNext = pLFH->pNext;
				pLFH->pNext->pPrev = pLFH->pPrev;
			}
		}
		delete pLFH;
	}
}

void DeleteAll()
{
	LPLFHHEAP pCurrent = m_pHead;

	while(pCurrent != NULL)
	{
		LPLFHHEAP pTemp = pCurrent->pNext;
		delete pCurrent;
		pCurrent = pTemp;
	}
}

// calculate our LFH allocation size
size_t GetAllocationSize( bool bLFH, size_t s )
{
	if(bLFH == false)
		return s;

	size_t nAlloc = 0;

	if( s <= 256 )
		nAlloc = (s + 7) & (-8);
	else if( s <= 512)
		nAlloc = (s + 15) & (-16);
	else if( s <= 1024)
		nAlloc = (s + 31) & (-32);
	else if( s <= 2048)
		nAlloc = (s + 63) & (-64);
	else if( s <= 4096)
		nAlloc = (s + 127) & (-128);
	else if( s <= 8196)
		nAlloc = (s + 255) & (-256);
	else if( s <= 16384 )
		nAlloc = (s + 511) & (-512);
	else 
		nAlloc = s;

	return nAlloc;
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Austria Austria
C++/C# developer (MSCD)
SQL DBA (MCDBA)

Comments and Discussions