lua-users home
lua-l archive

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


Thank you Viacheslav :)
Yes, I will implement the free() part as well to keep the memory under control.

Works now with output:  1 
Need to try out non-trivial cases now.

#include <string>

extern "C" {
    #include <lua.h>
    #include <lauxlib.h>
    #include <lualib.h>
}

char buffer[1048576];
char backupBuffer[1048576];
char *pTop = buffer;

void* customLuaAlloc(void* userData, void* ptr, size_t oldSize, size_t newSize)
{
    if (newSize == 0)
    {
        //free(ptr);
        return 0;
    }
    else {
        //return realloc(ptr, newSize);
        if (ptr != NULL) {
            // Copy contents
            memcpy(pTop, ptr, oldSize);
        }
        ptr = NULL;
        char *pOldTop = pTop;
        pTop += newSize;
        return (void*)pOldTop;
    }
}

int main()
{
    lua_State* L = lua_newstate(customLuaAlloc, NULL);

    luaL_openlibs(L);

    luaL_dostring(L, "a = 1");
    memcpy(backupBuffer, buffer, 1048576);

    luaL_dostring(L, "a = 2");

    memcpy(buffer, backupBuffer, 1048576);
    luaL_dostring(L, "print(a)");

    lua_close(L);
}


Thanks,
Abhijit

On Sat, Nov 2, 2019 at 11:57 PM Viacheslav Usov <via.usov@gmail.com> wrote:
On Sat, Nov 2, 2019 at 2:10 PM Abhijit Nandy <abhijit.nandy@gmail.com> wrote:

> If I comment out:  memcpy(backupBuffer, buffer, 4096)    then things are fine.

No they are not. Your buffers are too small and you have a buffer overrun in any case. However, with the memcpy in place, it modifies the the content of the overrun memory so you see the problem earlier.

Another problem is that you call luaL_newstate() and then lua_setallocf(). The first call will already have allocated some memory using the default allocator. This is benign for now, but may bite you in future. Use lua_newstate() instead.

Cheers,
V.