-2

I'm currently working on a project where I want to use SQLite to store some data. Everything is working well except when I want to insert new data into the table. When I run the application, I get segmentation fault, but I can't find the problem.

 void sqlite(char *id, char *sensorname, char *sensorvalue){
       sqlite3 *db;
       char *zErrMsg = 0;
       int rc;
       char *sql;
       const char* data = "Callback function called";

       /* Open database */
       rc = sqlite3_open("/home/macho/Documents/sensor_database.db", &db);
       if( rc ){
          fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
          exit(0);
       }else{
          fprintf(stderr, "Opened database successfully\n");
       }

        sql =   "INSERT INTO sensors (id,sensorname,sensorvalue) VALUES(";
       char* split = ",";
       strcat(sql, id);
       strcat(sql, ",");
       strcat(sql, sensorname);
       strcat(sql, ",");
       strcat(sql, sensorvalue);
       strcat(sql, ");");
       rc = sqlite3_exec(db, sql, callback, (void*)data, &zErrMsg);
       if( rc != SQLITE_OK ){
         fprintf(stderr, "SQL error: %s\n", zErrMsg);
         sqlite3_free(zErrMsg);
       }else{
         fprintf(stdout, "Operation done successfully\n");
   }
   sqlite3_close(db);
}

And in the main, I'm calling the sqlite() function:

sqlite("1","sensor","sensor1"); 

Any idea what the problem can be?

Thanks!

user2466860
  • 67
  • 1
  • 2
  • 13

1 Answers1

3

You assign sql a static (read-only) string and then attempt to append to it. Instead, create a large writeable array either on the stack or use malloc and then assemble your query in that. So

char sql[4096];
strcpy(sql, "INSERT INTO sensors ...
...

Note that you should check for overflow of the buffer based on the lengths of the values.

BTW, the code as written is just asking for an SQL injection attack if accessible to users. Look up Bobby Tables.

DrC
  • 7,528
  • 1
  • 22
  • 37
  • 2
    If this is _really_ a c++ question as tagged, you just use `std::ostringstream` instead of concatenating C strings manually. – Useless Mar 06 '15 at 16:48
  • @DrC Thanks for replay! I get another error now after changing to this: char sql[4096]; strcpy(sql, "INSERT INTO sensors (id,sensorname,sensorvalue) VALUES("+id+","+sensorname+","+sensorvalue+");"); The error I get now is: main.c:64: error: invalid operands to binary + (have ‘char *’ and ‘char *’) – user2466860 Mar 06 '15 at 17:00