lua-users home
lua-l archive

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


On 11/28/2014 11:07 PM, Tim Hill wrote:

      
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



Yeah that's true for Lua 5.2 and as I use that version so I should have known it. My code still should work for Lua 5.1 as there the reference states "ptr is NULL if and only if osize is zero".

And I don't know why casting a void* to a stuct pointer is safer than casting it to anything else. It's unsafe either way.
--
Thomas