Sqlite3_column_text returned data is corrupted during finalization / closing

I'm not sure what is happening here, but I found that the returned data from sqlite3_column_text changes during the sqlite completion / closing stage.

// rc not handled in this abbreviated code sqlite3 *db; sqlite3_stmt *stmt; char * sql; const char * tail; int rc; char * dbName = "C:\\db\\myblobs.db"; int myIndex = 0; char * myLocation1; string myLocation2; rc = sqlite3_open(dbName, &db); sql = "SELECT location FROM blobs WHERE key = ?"; rc = sqlite3_prepare(db, sql, strlen(sql), &stmt, &tail); sqlite3_bind_int(stmt, 1, myIndex); rc = sqlite3_step(stmt); myLocation1 = (char*)sqlite3_column_text(stmt, 0); myLocation2 = (char*)sqlite3_column_text(stmt, 0); // can process myLocation1 & myLocation2 fine here sqlite3_finalize(stmt); // data myLocation1 points to get corrupted sqlite3_close(db); // data myLocation2 points to gets further corrupted 

The problem is with myLocation1. The data that he points out is good until they fall into the sqlite3_finalize and sqlite3_close statements. However, mylocation2 remains unchanged. Therefore, I’m not sure what is happening here. After executing sqlite3_close (db), myLocation1 is identified as "Bad Ptr" in Visual Studio 2010.

Any help is most appreciated.

+6
source share
1 answer

From the exact guide :

const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
[...]
The returned pointers are valid until a type conversion occurs as described above, or until sqlite3_step() or sqlite3_reset() or sqlite3_finalize() called.

So, as soon as you call sqlite3_finalize , the returned values ​​from sqlite3_column_text become invalid, and the pointers myLocation1 and myLocation2 point to garbage.

If you need these lines after calling sqlite3_finalize , you will have to copy them to the memory that you control. In fact, because they are valid until the inverse of the type conversion happens, you must copy them immediately and use (char*)sqlite3_column_text(stmt, 0); only when creating your own copies.

+8
source

Source: https://habr.com/ru/post/905588/


All Articles