
#include "StdAfx.h"


SMemoryAllocationInfo *pFirstMemoryAllocation = NULL;


void *safe_malloc
	( size_t allocationSize,
	  char *filename,
	  int nLine )
{
	size_t size = allocationSize + sizeof(SMemoryAllocationInfo) + noMansLandSize;

    //	round requested size + extra bookkeeping space to appropriate boundry size
    size = ROUND_TO_POWER_OF_TWO(size, 4);
	
	//	allocate memory
	void *allocation = malloc( size );

	//	fill in header information
	SMemoryAllocationInfo *header = (SMemoryAllocationInfo *) allocation;
	header->size = allocationSize;
	header->filename = filename;
	header->nLine = nLine;

	//	add to linked list of all allocations
	header->pPrevious = NULL;
	header->pNext = pFirstMemoryAllocation;
	if( pFirstMemoryAllocation != NULL )
		pFirstMemoryAllocation->pPrevious = header;
	pFirstMemoryAllocation = header;

	//	fill in no-mans-land buffer zone with specific data
	memset( &(header->noMansLand), 0x7D, noMansLandSize );
	memset( (byte *) allocation + sizeof(SMemoryAllocationInfo) + allocationSize, 0x7D, noMansLandSize );

	//	fill main memory allocation with specific data
	memset( (byte *) allocation + sizeof(SMemoryAllocationInfo), 0xBB, allocationSize );

	//	return main memory allocation
	return (byte *) allocation + sizeof(SMemoryAllocationInfo);
}
