I'm trying to something really basic - returning the result of the SELECT statement using C/C++ interface for SQLite. My Data table has only two fields - key (varchar) and value (text).
Given the key, my goal is to return the value by querying the SQLite database. I pass to *sqlite3_exec* - *select_callback* function as well as param (char *). The param is successfully set to the correct value within *select_callback*. However, after calling *sqlite3_exec* param points to an empty string (despite pointing to the same memory).
Any idea what's going wrong and how to fix this? Does *sqlite3_exec* deallocate memory for param behind the scenes?
Thank you in advance!
// given the key tid returns the value
void getTypeByID(sqlite3 * db, string tid)
{
string sql_exp_base = "select value from Data where key=''";
int len = (int)sql_exp_base.size() + (int)tid.size() + 10;
char * sql_exp = new char[len];
sprintf(sql_exp, "select value from Data where key='%s'", tid.data());
sql_exec(db, sql_exp);
}
// This is the callback function to set the param to the value
static int select_callback(void * param, int argc, char **argv, char **azColName)
{
if(argc == 0) return 0;
char * res = (char *)param;
res = (char *) realloc(res, sizeof(*res));
res = (char *) malloc(strlen(argv[0]) + 1);
strcpy(res, argv[0]);
printf("%s\n", res); // {"name": "Instagram Photo", url: "http://instagram.com"}
return 0;
}
// execute the SQL statement specified by sql_statement
void sql_exec(sqlite3 * db, const char * sql_statement)
{
char * zErrMsg = 0;
char * param = (char *)calloc(1, sizeof(*param));
int rc = sqlite3_exec(db, sql_statement, select_callback, param, &zErrMsg);
printf("%s\n", param);
param SHOULD BE {"name": "Instagram Photo", url: "http://instagram.com"}, BUT IT IS EMPTY STRING FOR SOME REASON!
if(rc != SQLITE_OK)
{
fprintf(stderr, "SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
}
}
sizeof(*res)?! It's a compile-time-evaluated expression, equals to 1.