Arman
Arman

Reputation: 1084

SQLite in C/C++. sqlite3_exec: parameter set in callback function is pointing to an empty string

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);
    }
}

Upvotes: 2

Views: 10180

Answers (2)

Oren Oichman
Oren Oichman

Reputation: 33

I tried the last answer and it worked for me : I have created a pointer to pointer as a char value and insert the pointer of pointer from the void variable

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sqlite3.h>


int callback(void *data,int argc,char *argv[],char **azcolname) {
int i=0;

char **result_str = (char **)data;
*result_str = (char *)calloc(strlen(argv[0]),sizeof(char));
strcpy(*result_str,argv[0]);
return 0;
}

    int main(int argc,char *argv[]) {

sqlite3 *conn;
int c=0;
char *ofile=NULL;
char *tsql_stmt=NULL;
int res=0;
char *zErrMsg = 0;
char *data=NULL;


while((c = getopt(argc , argv ,"f:")) != -1) 
{
    switch (c) {

        case 'f':
            ofile = optarg;
        break;

        default:
            fprintf(stderr,"worng argument provided\n");
        break;

    }
}

if (!ofile) {
    fprintf(stderr,"no output file (-f) given\n");
    exit(1);
}
sqlite3_open(ofile,&conn);
tsql_stmt = calloc(80,sizeof(char));
strcpy(tsql_stmt,"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='");
    strcat(tsql_stmt,"mytest");
    strcat(tsql_stmt,"\'");

    //running the query
//printf("%s\n",tsql_stmt);
res = sqlite3_exec(conn,tsql_stmt,callback,&data, &zErrMsg);

if ( res != SQLITE_OK ) {
    fprintf(stderr, "SQL error: %s\n", zErrMsg);
    sqlite3_free(zErrMsg);
}
else{
    if ( atoi(data) != 1)
        fprintf(stderr, "unable to find the requested table\n");
    else
        printf("the Operation found the requested table in the database\n");
}

free(data);
sqlite3_close(conn);
return 0;
}

Upvotes: 0

CL.
CL.

Reputation: 180070

You are writing the pointer to the newly allocated memory into res, but that variable is a local variable inside select_callback, so sql_exec will not know about it. The same applies to the param parameter: it is just a copy of sqlite3_exec's fourth parameter.

To ensure that your changes to the string are seen, you have to pass a pointer to the string itself (which is a pointer in C, or could be a string object in C++), similar to the error message. For C:

char *result_str = ...;
rc = sqlite3_exec(..., &result_str, ...);
...
int callback(void *param, ...)
{
    char **result_str = (char **)param;
    *result_str = (char *)realloc(*result_str, ...);
    strcpy(*result_str, ...);
}

Note: You will get problems when the tid string contains quotes or other control characters, or when you try to search for Bobby Tables. Use sqlite3_mprintf to format and allocate the SQL string, or better use parameters.

Upvotes: 4

Related Questions