lua-users home
lua-l archive

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


On Sat, Feb 21, 2009 at 5:18 PM, Bertrand Mansion <lua@mamasam.net> wrote:
> On Sat, Feb 21, 2009 at 3:47 PM, Jerome Vuarand
> <jerome.vuarand@gmail.com> wrote:
>> 2009/2/21 Bertrand Mansion <lua@mamasam.net>:
>>> I am trying to create a C module for Lua. One of the functions deals
>>> with string quoting so I need to allocate a buffer with 2 times +1 the
>>> memory occupied by the source string. Usually, I would use malloc()
>>> but I noticed that there is a lmem.h file with a luaM_malloc()
>>> function, so I could write something like this:
>>>  to = luaM_malloc(L, 2 * size);
>>>
>>> Unfortunately, #include "lmem.h" doesn't work if I install Lua using
>>> the default Makefile (I am on Macosx). Is there a way to build Lua or
>>> some extra steps I should do manually in order to be able to use
>>> "lmem.h" ? Thanks,
>>
>> You have two normal ways to allocate memory with Lua. You can either
>> call lua_getallocf to retrieve Lua's memory allocator and use it. You
>> can also create a userdata on the stack with lua_newuserdata. The
>> interesting aspect of using a userdata is that it is garbage
>> collected, and you don't have to take care of de-allocation, even in
>> the case of Lua errors.
>
> Thanks Jérome, but here is my code:
>
>    size_t slen, dlen;
>    const char *src = luaL_checklstring(L, 1, &slen);
>    char *buf;
>
>    slen = luaL_optlong(L, 2, slen);
>    buf = (char*)malloc(2 * slen);
>    dlen = apreq_quote(buf, src, slen);
>    lua_pushlstring(L, buf, dlen);
>    free(buf);
>    return 1;
>
> How would I then use lua_getallocf instead of malloc/free ?
> (I tried but got a segfault)

Replying to myself... here is how I did it and it worked:

    size_t slen, dlen;
    const char *src = luaL_checklstring(L, 1, &slen);
    char *buf;
    void *ud;

    lua_Alloc f = lua_getallocf(L, &ud);
    slen = luaL_optlong(L, 2, slen);
    buf = (*f)(ud, NULL, 0, (2 * slen));
    dlen = apreq_quote(buf, src, slen);
    lua_pushlstring(L, buf, dlen);
    (*f)(ud, buf, (2 * slen), 0);
    return 1;

Is there something wrong with this code ?
Also, is there something wrong in using malloc/free in Lua modules ?


-- 
Bertrand Mansion
Mamasam