SQLite Forum

sqlite3_value_dup and stale pointers
Login

sqlite3_value_dup and stale pointers

(1) By anonymous on 2022-03-14 19:32:21 [source]

With SQLite 3.37, this example program

    #include <stdio.h>
    #include <sqlite3.h>

    static void destroy(
        void *data)
    {
        printf("pointer %p has been destroyed\n",data);
    }

    int main(void)
    {
        static char const sql[]="select ?";
        sqlite3 *connection;
        sqlite3_stmt *stmt;
        sqlite3_value *orig,*cloned;

        sqlite3_open("",&connection);
        sqlite3_prepare_v2(connection,sql,sizeof sql,&stmt,NULL);
        sqlite3_bind_pointer(stmt,1,"whatever","example",destroy);
        sqlite3_step(stmt);
        orig=sqlite3_column_value(stmt,0);
        cloned=sqlite3_value_dup(orig);
        sqlite3_finalize(stmt);
        printf("sqlite3_value_pointer returned %p\n",
               sqlite3_value_pointer(cloned,"example"));
        sqlite3_value_free(cloned);
        sqlite3_close(connection);
        return 0;
    }

generates this output

    pointer 0x10893ff5c has been destroyed
    sqlite3_value_pointer returned 0x10893ff5c

which I claim is a bad thing.

The quick fix is to make sqlite3_value_dup return an ordinary null value in this situation.

A thorough fix would probably have to involve a reference counted layer of indirection, which might also be useful for text and blob value buffers.

(2) By Richard Hipp (drh) on 2022-03-14 23:52:11 in reply to 1 [link] [source]

Now on trunk, the sqlite3_value_dup() returned for a pointer is just a NULL value.

(3) By anonymous on 2022-03-15 13:02:29 in reply to 2 [link] [source]

Thanks!