Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lua_pushstring failures result in leaked memory #5

Open
daurnimator opened this issue Jun 4, 2015 · 2 comments
Open

lua_pushstring failures result in leaked memory #5

daurnimator opened this issue Jun 4, 2015 · 2 comments

Comments

@daurnimator
Copy link
Owner

If lua_pushstring longjmps out then the string is never freed.

e.g.

lua_pushstring(L, session);

@daurnimator
Copy link
Owner Author

Possible solution via pcalling:

static int pointer_to_string (lua_State *L) {
    lua_pushstring(L, lua_topointer(L, 1))
    return 1;
}

static void pushstring_and_free (lua_State *L, char* str) {
    int err;
    lua_pushcfunction(L, pointer_to_string);
    lua_pushlightuserdata(L, str);
    err = lua_pcall(L, 1, 1, 0);
    free(str);
    if (LUA_OK != err) lua_error(L);
}

.....

    pushstring_and_free(L, str);

Uses lua_pushcfunction and lua_pushlightuserdata as they can't fail (as long as there is stack space).
In lua 5.1, lua_cpcall has to be used instead, however it doesn't leave return values on the stack; so needs gymnastics via the registry or something.

@daurnimator
Copy link
Owner Author

Alternative solution is via allocating a copy (via e.g. luaL_prepbuffsize), freeing the original, then pushing the buffer result.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant