lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On Monday 07, HyperHacker wrote:
> In C/C++ I often find myself wishing I could globally redefine malloc,
> free, new and delete to print debugging info to track down
> memory-related bugs... in Lua you can do this kind of thing as easily
> as shown above!

You can intercept calls to malloc()/free()/etc.., by using the "--wrap" linker 
option (See manpage for ld).

With gcc you can use the following option:

Then you create wrapper functions like:
void * __wrap_malloc(size_t size) {
  printf("malloc called with %zu\n", size);
  return __real_malloc(size);

I have used this trick to log the memory usage of long running services to 
detect memory leaks.  You can pre-append a header structure to all allocations 
to track the memory block size, so the free()/realloc() functions know the 
block size.  This will also work for C++ code since 'new' calls malloc to 
allocate memory for objects.  Also this should intercept alloc calls from 
other libraries too.

Now when I am writing C code I use an allocator function like the one the Lua 
VM uses, since it allows memory usage tracking without wasting memory to track 
the size of each allocated block.

Robert G. Jakabosky