SQLite Forum

sqlite3_deserialize double memory freeing
I'm experiencing a double free in SQLite code on close when using sqlite3_deserialize.  The C library complains: **free(): double free detected in tcache 2** as does valgrind complain in the sqlite3_close.

Specifically I serialize the main db, and then deserialize it into the temp db.  Full code is at [https://gist.github.com/rogerbinns/d11994c1d85e36c341e20f25ec491f5e](https://gist.github.com/rogerbinns/d11994c1d85e36c341e20f25ec491f5e)

Extract (leaving out error checking for clarity - error checking is in gist):

    /* in memory db with default flags */
    res = sqlite3_open_v2("", &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);

    /* create a table so the database is not empty */
    res = sqlite3_exec(db, "create table foo(x)", NULL, NULL, NULL);

    /* serialize */
    serialized = sqlite3_serialize(db, "main", &serial_size, 0);

    /* copy the data */
    datacopy = sqlite3_malloc64(serial_size);
    memcpy(datacopy, serialized, serial_size);

    /* free serialized (caller is responsible for freeing the returned value to avoid a memory leak) */

    /* now load data into temp */
    res = sqlite3_deserialize(db, "temp", datacopy, serial_size, serial_size, SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE);


Any ideas?