sqlite3_column_text 返回的数据在完成/关闭期间被破坏 [英] sqlite3_column_text returned data gets corrupted during finalize/close
问题描述
我不确定这里发生了什么,但我发现从 sqlite3_column_text 返回的数据在完成/关闭 sqlite 阶段被改变了.
I'm not sure what's happening here but I'm finding that the returned data from sqlite3_column_text is being altered during the finalize/close sqlite 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
问题与 myLocation1 相关.它指向的数据很好,直到它遇到 sqlite3_finalize 和 sqlite3_close 语句.但是 mylocation2 保持不变.所以不确定这里发生了什么.执行 sqlite3_close(db) 后,myLocation1 在 Visual Studio 2010 中被识别为Bad Ptr".
The problem is in relation to myLocation1. The data it points to is fine until it hits the sqlite3_finalize and sqlite3_close statements. However mylocation2 remains unaltered. So not sure what's happening here. After executing sqlite3_close(db), myLocation1 is identified as a "Bad Ptr" within Visual Studio 2010.
非常感谢任何帮助.
推荐答案
来自精美手册一个>:
const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
[...]
返回的指针一直有效,直到发生如上所述的类型转换,或者直到 sqlite3_step()
或 sqlite3_reset()
或 sqlite3_finalize()
被调用.
const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
[...]
The pointers returned are valid until a type conversion occurs as described above, or untilsqlite3_step()
orsqlite3_reset()
orsqlite3_finalize()
is called.
因此,只要您调用 sqlite3_finalize
,sqlite3_column_text
的返回值就会无效,并且您的 myLocation1
和 myLocation2
> 指针指向垃圾.
So as soon as you call sqlite3_finalize
, the return values from sqlite3_column_text
become invalid and your myLocation1
and myLocation2
pointers point to garbage.
如果您在调用 sqlite3_finalize
后需要这些字符串,那么您必须将它们复制到您控制的内存中.事实上,由于在发生类型转换之前都是有效的注意,你应该立即复制它们并且只使用 (char*)sqlite3_column_text(stmt, 0);
而你正在制作自己的副本.
If you need those strings after you call sqlite3_finalize
then you'll have to copy them into memory that you control. In fact, due to the are valid until a type conversion occurs note, you should copy them immediately and only use (char*)sqlite3_column_text(stmt, 0);
while you're making your own copies.
这篇关于sqlite3_column_text 返回的数据在完成/关闭期间被破坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!