【发布时间】:2015-01-02 03:43:49
【问题描述】:
首先,我有以下代码:
map<char*, char*> records;
// id, value are buffer variables to store the text that returns from `strcpy()`
char *id = (char*)malloc(sizeof(char*) * 20);
char *value = (char*)malloc(sizeof(char*) * 20);
sql->open(dbFile);
sql->query("SELECT * FROM categories");
while(sql->fetch() != SQLITE_DONE){
// copy the text that returns from `sql->getValue`, then convert that text from `const unsigned char*` to `const char*`
strcpy(id, reinterpret_cast<const char*>(sql->getValue(0)));
strcpy(value, reinterpret_cast<const char*>(sql->getValue(1)));
// insert the values that in `id`,`value` as new item
records.insert(pair<char*, char*>(id, value));
}
free(id);
free(value);
前面代码的想法是使用strcopy()复制返回此方法sql->getValue(0)的文本,然后将该文本从const unsigned char*转换为const char*,然后将这些文本存储在id,@ 987654327@ 变量,然后插入id、value 作为新项目。
前面的步骤发生在从数据库获取的每个数据上。
进一步澄清这个想法:
例如,从数据库中提取了三行(fruits、vegetables、sweets)。
自然,将这三个数据插入地图容器时,容器中的项目数将是三个项目first(fruits),second(vegetables )、第三(sweets)。
在我的情况下,当检查项目数量时,我发现只有一项,项目是sweets。
现在,我很惊讶,剩下的物品在哪里?
【问题讨论】:
-
您用于
std::map的密钥不是id,它是char*到id。我建议你使用std::string,因为我认为你也有内存泄漏。 -
您在上一个问题中被告知,
char*的地图是一个糟糕的设计。可以这样做,但您会遇到内存管理混乱,就像在这段代码中一样。 -
@Galik:谢谢,确切地说,我知道这一点,但不知道如何在不使用字符串类型的情况下解决问题。
-
@Blastfurnace:是的,但我只使用 stl 映射来模拟关联数组。
-
@LionKing:每次调用
insert()时,您都会为键/值对传递相同的地址。这就是std::map看到的所有内容,两个指针。它不遵循指针来查看字符串或进行复制。您可能会在调用之间修改char数组的内容,但std::map不知道这一点。在循环之后,您free()将在std::map中留下悬空指针的内存。