c - Sqlite3 - 试图在回调中填充结构

标签 c memory struct sqlite malloc

我有以下结构:

typedef struct {
    char *username;
    char *score;
} Highscore;

使用方法如下:

static int callback(void* data, int argc, char** argv, char** colName) {
  Highscore* highscore = (Highscore*)data;

  highscore->username = argv[0];
  highscore->score = argv[1];

  return 0;
}

数据库编排在这里与结构一起使用:

Highscore* getHighscore()
{
  sqlite3* db_handle;
  int rc;
  char* zErrMsg;
  Highscore* highscore = malloc(sizeof(Highscore));
  /* highscore->username = malloc(sizeof(100)); */
  /* highscore->score = malloc(sizeof(100)); */

  //Datenbankverbindung oeffnen
  rc = sqlite3_open(DATABASE_FILE, &db_handle);

  char* sSqlString = sqlite3_mprintf
    ("select U.Username, H.Punkte from Highscore H join User U on U.B_ID = H.B_ID order by Punkte desc limit 10");

  //SQL Statement ausfuehren
  rc = sqlite3_exec(db_handle, sSqlString, callback, highscore, &zErrMsg);

  //Datenverbindung schliessen und Speicher leeren
  sqlite3_free(sSqlString);
  rc = sqlite3_close(db_handle);

  return highscore;

}

现在出现的问题是,在回调范围内,Highscore 结构已按应有的方式分配字段“username”和“score”。我在那个位置调试,一切正常。

但是当我回到“getHighscore”的范围时,Highscore 结构的字段中有任意值。我不知道发生了什么事?在使用“malloc”将其提供给回调之前,我已经分配了该结构。而且我已经检查了它是否与回调后的地址相同 - 它是。那么为什么值会损坏?

最佳答案

Highscore 结构中只保留指针,实际值会被覆盖。试试这个:

static int callback(void* data, int argc, char** argv, char** colName)
{
  Highscore* highscore = (Highscore*)data;

  highscore->username = malloc( strlen( argv[0] ) + 1 );
  strcpy( highscore->username, argv[0] );
  highscore->score = malloc( strlen( argv[1] ) + 1 );
  strcpy( highscore->score, argv[1] );

  return 0;
}

不要忘记 free scoreusername 最后(在 free-ing 高分).

关于c - Sqlite3 - 试图在回调中填充结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36791684/

相关文章:

c - 关于C中数组相等的问题

python - 打包 bool 数组需要通过 int (numpy 1.8.2)

python-3.x - 使用 Python 3 从 Linux 上的内存加载库

c - 使用结构取消引用指向不完整类型的指针

不能为每个元素洗牌一次

c - 字母 A 和 M 对预处理器意味着什么

使用位域比较 C 中的结构

python - 以类型化内存 View 作为成员的结构定义

c - sizeof 在添加和计算时如何针对不同的数据类型工作?

c# - 列表在不应该使用重复数据时填充