sqlite global variable bug
I have a global variable named mob
. When I print it the first time it is what I expect: 'Wolf'. But when I print it again in the end of main
, it looks like 'до'. I debugged this code a lot and mob
is global so I don't understand how it could be changed. I can add comments to part of the code if necessary.
I'm using sqlite3, Visual Studio 2010 and Win 7 x64.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "sqlite3.h"
struct Mob {
Mob():_name(0),_lvl(0),_loot(0){}
unsigned const char* _name;
unsigned const char* _lvl;
unsigned const char* _loot;
}mob;
void main()
{
sqlite3 *db;
sqlite3_stmt * pStmt;
int i, j, coln, rc;
int b = 1;
char *sql[] = {
"CREATE TABLE tbl (name TEXT,lvl INTEGER,loot TEXT);",
"INSERT开发者_Go百科 INTO tbl VALUES('Wolf',5,'Meat');",
"SELECT * FROM tbl;"
};
if (sqlite3_open("exam2.db", &db))
{
printf("Error: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
system("pause");
exit(1);
}
for (i=0; i<sizeof(sql)/sizeof(sql[0]); i++)
{
if (sqlite3_prepare(db, sql[i], -1, &pStmt, NULL))
{
printf("Error: %s\n", sqlite3_errmsg(db));
sqlite3_finalize(pStmt);
sqlite3_close(db);
system("pause");
exit(1);
}
coln = sqlite3_column_count(pStmt);
while((rc = sqlite3_step(pStmt)) == SQLITE_ROW)
{
coln = sqlite3_data_count(pStmt);
mob._name=sqlite3_column_text(pStmt, 0);
std::cout<<mob._name<<std::endl; //1
}
if (rc != SQLITE_DONE) printf("Error: %s\n",
sqlite3_errmsg(db));
sqlite3_finalize(pStmt);
}
std::cout<<mob._name<<std::endl; //2
sqlite3_close(db);
system("pause");
} //end main
Mob::_name
is a raw pointer and you set it to a string that is owned and managed by SQLite. When you try to output the string again SQLite has already reused that memory, so your program runs into undefined behavior and you see garbage printed.
You should deep-copy the string - preferably by using std::string
to store it.
精彩评论