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

strbuf_free causes Bus error or SIGSEGV #98

Open
hyw0810 opened this issue Jan 27, 2024 · 0 comments
Open

strbuf_free causes Bus error or SIGSEGV #98

hyw0810 opened this issue Jan 27, 2024 · 0 comments

Comments

@hyw0810
Copy link

hyw0810 commented Jan 27, 2024

When DEFAULT_ENCODE_KEEP_BUFFER is 0, strbuf_free will cause Bus error or SIGSEGV. Please see the code below:

#define DEFAULT_ENCODE_KEEP_BUFFER 0

void strbuf_free(strbuf_t *s)
{
    debug_stats(s);

    if (s->buf) {
        free(s->buf);
        s->buf = NULL;
    }
    if (s->dynamic)
        free(s);
}

static int json_destroy_config(lua_State *l)
{
    json_config_t *cfg;

    cfg = lua_touserdata(l, 1);
    if (cfg)
        strbuf_free(&cfg->encode_buf);
    cfg = NULL;

    return 0;
}

static void json_create_config(lua_State *l)
{
    json_config_t *cfg;
    int i;

    cfg = lua_newuserdata(l, sizeof(*cfg));
    // memset(cfg, 0, sizeof(*cfg)) should be called here

    /* Create GC method to clean up strbuf */
    lua_newtable(l);
    lua_pushcfunction(l, json_destroy_config);
    lua_setfield(l, -2, "__gc");
    lua_setmetatable(l, -2);

    ...

#if DEFAULT_ENCODE_KEEP_BUFFER > 0
    strbuf_init(&cfg->encode_buf, 0);           // will not be called
#endif
}

In the json_create_config function, DEFAULT_ENCODE_KEEP_BUFFER is 0 and strbuf_init function will not be called.

When cfg = lua_newuserdata() is called, should check whether cfg is NULL. If it is not NULL, should call memset function, otherwise cfg->encode_buf.buf may not be NULL.

When the program exits json_destroy_config function calls strbuf_free function. When strbuf_free checks that cfg->encode_buf.buf is not NULL, and attempts to release memory results in an error.

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