views:

1090

answers:

4

Assuming the latest XCode and GCC, what is the proper way to override the memory allocation functions (I guess operator new/delete as well). The debugging memory allocators are too slow for a game, I just need some basic stats I can do myself with minimal impact.

I know its easy in Linux due to the hooks, and this was trivial under codewarrior ten years ago when I wrote HeapManager.

Sadly smartheap no longer has a mac version.

A: 

The malloc_default_zone technique mentioned at http://lists.apple.com/archives/darwin-dev/2005/Apr/msg00050.html appears to still work, see e.g. http://code.google.com/p/fileview/source/browse/trunk/fileview/fv_zone.cpp?spec=svn354&r=354 for an example use that seems to be similar to what you intend.

Alex Martelli
A: 

If the basic stats you need can be collected in a simple wrapper, a quick (and kinda dirty) trick is just using some #define macro replacement.

void* _mymalloc(size_t size)
{
    void* ptr = malloc(size);

    /* do your stat work? */

    return ptr;
}

and

#define malloc(sz_) _mymalloc(sz_)

Note: if the macro is defined before the _mymalloc definition it will end up replacing the malloc call inside that function leaving you with infinite recursion... so ensure this isn't the case. You might want to explicitly #undef it before that function definition and simply (re)define it afterward depending on where you end up including it to hopefully avoid this situation.

This won't work with C++ operator new/delete or libraries without source though
codist
A: 

I think if you define a malloc() and free() in your own .c file included in the project the linker will resolve that version.

Now then, how do you intend to implement malloc?

Joshua
+1  A: 
Sam Hocevar