Memory handlers

Discuss about anything related to the Irrlicht Engine, or read announcements about any significant features or usage changes.
Post Reply
Razed
Posts: 9
Joined: Mon May 10, 2004 9:43 am

Memory handlers

Post by Razed »

Here's some stuff I've added to my own 0.6 version thay may be useful in general. The main idea is to be able to specify my own malloc/free functions (I've got some with memory tracking to ensure there aren't any memory leaks).

I added two arguments to the CreateDevice function, the function pointers of a malloc/free handlers, or null for none. The handler functions are:
typedef void* MallocHandler(size_t a_iSize, const char* a_szFile, int a_iLine)
typedef void FreeHandler(void* a_pData)

Then I overloaded new & delete operators with:
void* operator new(size_t a_iSize)
{
if (0 != g_pfnMallocHandler)
return (*g_pfnMallocHandler)(a_iSize, "", -1);
else
return malloc(a_iSize);
}
void operator delete(void* a_pData)
{
if (0 != g_pfnFreeHandler)
(*g_pfnFreeHandler)(a_pData);
else
free(a_pData);
}

That got things working, although with no tracking info. To add that requires a bit of extra searching+replacing. The way I got it to work was to insert code into the irrtypes.h (which is pretty much a global include), with

#if defined(IRRLICHT_EXPORTS)
operator new(size_t, const char*, int);
#endif
#if defined(_DEBUG)
#define IrrNew new(__FILE__, __LINE__)
#else
#define IrrNew new
#endif

After adding another operator new (with file and line args), and a large replace of 'new' to 'IrrNew', pretty much everything worked.

With the tracking turned on, the exta allocs turned out to be scene animator nodes, which obviously require an extra 'drop' after they are attached to a scene node. After I fixed those in my app, it went in and out with 0 remaining allocs, which I was very impressed with.
Post Reply