Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlite3_bind_blob when is safe to free memory?

Tags:

c

sqlite

I have such working code:

const char sql[] = "INSERT INTO test (pk, geom) VALUES (?, ?)";
sqlite3_stmt *stmt;
sqlite3_prepare_v2 (handle, sql, strlen (sql), &stmt, NULL);

for (...) {
        sqlite3_reset (stmt);
        sqlite3_clear_bindings (stmt);
        int blob_size = ..;
        unsigned char *blob = malloc(blob_size);
        sqlite3_bind_int64 (stmt, 1, pk);
        sqlite3_bind_blob (stmt, 2, blob, blob_size, free);
        sqlite3_step (stmt);
}

I wonder is it possible to not allocate and free on every step of cycle? If I pass SQLITE_STATIC instead of free to sqlite3_bind_blob and call free after end of cycle is this code still become valid?

const char sql[] = "INSERT INTO test (pk, geom) VALUES (?, ?)";
sqlite3_stmt *stmt;
sqlite3_prepare_v2 (handle, sql, strlen (sql), &stmt, NULL);
int capacity = 1024;
unsigned char *blob = malloc(capacity);

for (...) {
        sqlite3_reset (stmt);
        sqlite3_clear_bindings (stmt);
        int blob_size = ..;
        if (capacity < blob_size) {
           blob = realloc(blob, blob_size);
           capacity = blob_size;
        }
        sqlite3_bind_int64 (stmt, 1, pk);
        sqlite3_bind_blob (stmt, 2, blob, blob_size, SQLITE_STATIC);
        sqlite3_step (stmt);
}
free(blob);
like image 478
user1244932 Avatar asked Sep 19 '25 19:09

user1244932


1 Answers

Using SQLITE_STATIC requires that the value stays valid as long as the statement might access it.

Your code should be valid; but to be sure, move the call to sqlite3_clear_bindings() (and the reset) to the end of the loop.

like image 51
CL. Avatar answered Sep 22 '25 10:09

CL.