MemMgr (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the use of the SetMemoryManager and GetMemoryManager routines. Note that this example is thread-safe.


bool isMyMemMgr; TMemoryManagerEx oldMemMgr; volatile long getMemCalls; volatile long freeMemCalls; volatile long reallocMemCalls; volatile long allocMemCalls;

Code

void* __fastcall myGetMem(int size)
{
	//Safely increment the counter.
	InterlockedIncrement(&getMemCalls);

	//Route the call.
	return oldMemMgr.GetMem(size);
}

int __fastcall myFreeMem(void* p)
{
	//Safely increment the counter.
	InterlockedIncrement(&freeMemCalls);

	//Route the call.
	return oldMemMgr.FreeMem(p);
}

void* __fastcall myReallocMem(void* p, int size)
{
	//Safely increment the counter.
	InterlockedIncrement(&reallocMemCalls);

	//Route the call.
	return oldMemMgr.ReallocMem(p, size);
}

void* __fastcall myAllocMem(int size)
{
	//Safely increment the counter.
	InterlockedIncrement(&allocMemCalls);

	//Route the call.
	return oldMemMgr.AllocMem(size);
}

void __fastcall TForm3::btUseSysMemMgrClick(TObject *Sender)
{
	//Switch button states.
	btUseSysMemMgr->Enabled = false;
	btUseMyMemMgr->Enabled = true;

	//Set the old memory manager back.
	SetMemoryManager(oldMemMgr);

	isMyMemMgr = false;

    //Clear out the variables.
	getMemCalls     = 0;
	freeMemCalls    = 0;
	reallocMemCalls = 0;
	allocMemCalls   = 0;
}

void __fastcall TForm3::FormDestroy(TObject *Sender)
{
	//Set the old memory manager back.
	if (isMyMemMgr)
	{
        SetMemoryManager(oldMemMgr);
	}
}

void __fastcall TForm3::Timer1Timer(TObject *Sender)
{
	//Note that IntToStr calls will also Allocate/Free
	//memory; at each timer tick, the counts will be +4.

	Form3->edGetMem->Text = IntToStr((int)getMemCalls);
	Form3->edFreeMem->Text = IntToStr((int)freeMemCalls);
	Form3->edReallocMem->Text = IntToStr((int)reallocMemCalls);
	Form3->edAllocMem->Text = IntToStr((int)allocMemCalls);
}

void __fastcall TForm3::btUseMyMemMgrClick(TObject *Sender)
{
	TMemoryManagerEx myMemMgr;

	//Switch button states.
	btUseSysMemMgr->Enabled = true;
	btUseMyMemMgr->Enabled = false;

	//Get the old memory manager.
	GetMemoryManager(oldMemMgr);

    //Create out instance.
	myMemMgr.GetMem = myGetMem;
	myMemMgr.FreeMem = myFreeMem;
	myMemMgr.AllocMem = myAllocMem;
	myMemMgr.ReallocMem = myReallocMem;

    //Use defaults for this (not important).
	myMemMgr.RegisterExpectedMemoryLeak = oldMemMgr.RegisterExpectedMemoryLeak;
	myMemMgr.UnregisterExpectedMemoryLeak = oldMemMgr.UnregisterExpectedMemoryLeak;

	//Clear out the variables.
	getMemCalls     = 0;
	freeMemCalls    = 0;
	reallocMemCalls = 0;
	allocMemCalls   = 0;

	//Install the new memory manager.
	SetMemoryManager(myMemMgr);

	isMyMemMgr = true;
}

void __fastcall TForm3::btDoSomethingClick(TObject *Sender)
{
	void *ptr;
	//Perform memory allocation and deallocation.
	for (int i=0; i < 1000; ++i)
	{
		ptr = GetMemory(4);
		FreeMemory(ptr);
	}
}

Uses