Home > Mobile >  C , getting gibberish from const unisgned char array
C , getting gibberish from const unisgned char array

Time:11-14

I am trying to write a program with a simple login interface for school in C . I am new and still learning but I am getting a strange error with the following snippet of code. Inside the loop it outputs the username,password and name just as intended but if I try to access the array later it outputs gibberish. Any help with this is greatly appreciated:

EDIT: Thanks everyone! You suggestions helped to fix the problem. I needed to use strdup, It is not a standard c function but is really easy to implement, just run a google search!

sql = "SELECT username,password,real_name from Users"; 

const  unsigned char* usernames[20]; // 20 max usernames
const  unsigned char* passwords[20];
const  unsigned char* names[20];
rc =    sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);     //sqlite3_exec(db, sql, callback, usernames, &zErrMsg);


if( rc != SQLITE_OK ) {
      printf("error: %s ", sqlite3_errmsg(db));
   return 1;
   } 
   
   int i  = 0;
   while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
     
    usernames[i]= sqlite3_column_text (stmt, 0);
    passwords[i] = sqlite3_column_text(stmt, 1);
    names[i] = sqlite3_column_text(stmt, 2);
 //Prints fine
   cout << usernames[i] << ":" << passwords[i] << ":" << names[i] << "\n"; 
    i = i   1 ;
}

//Prints gibberish
cout << usernames[0];



CodePudding user response:

According to the documentation:

The pointers returned are valid [...] until sqlite3_step() or sqlite3_reset() or sqlite3_finalize() is called.

Since you are calling sqlite3_step on each iteration, the pointer you saved into the arrays became invalid right afterward.


Solution

Either manually invoke malloc and strcpy to actually store the result, or simply save them into std::strings.

  • Related