lua-users home
lua-l archive

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


> 
> Something like this (untested):
> static void theLuaAllocator (void *ud, void *ptr, size_t osize,
>                                                 size_t nsize) {
>     /* statistics */
>     *((int*)ud) += (nsize - osize); 
> 
>     /* allocation */
>     (void)ud;  (void)osize;  /* not used */
>        if (nsize == 0) {
>          free(ptr);
>          return NULL;
>        }
>        else
>          return realloc(ptr, nsize);
>      }
> Then:
> 
> int theMemoryCounter = 0;
> lua_State *L = lua_newstate (&theLuaAllocator, &theMemoryCounter);
> 
> That means you can write an allocator function that traces or tracks all memory allocations. If you use the standard Lua interpreter, you can easily change the lua.c file and build your own version to do the same.
> —

That won’t quite work as written, since when ptr is NULL “osize” contains the TYPE of object being allocated, not a size. You need:

*((int*)ud) += (nsize - (ptr ? osize : 0))

(Editorial: I don’t like coercing a pointer to an int like that; I think you are better/safer passing in a pointer to a struct containing an integer.)

—Tim