Ustring错误(打印期间)

时间:2013-07-12 11:01:00

标签: c++ utf-8 glib wofstream glibmm

我想将UTF-8文件解析为ustring,我在str中读取此文件。 有一个错误: 在抛出'Glib :: ConvertError'实例后终止调用。 我该怎么办?

char* cs = (char*) malloc(sizeof(char) * str.length());
strcpy(cs, str.c_str());
ustring res;
while (strlen(cs) > 0) {
    gunichar ch = g_utf8_get_char(cs);
    res.push_back(ch);
    cs = g_utf8_next_char(cs);
}
wofstream wout("output");
cout << res << endl;

1 个答案:

答案 0 :(得分:1)

这看起来非常错误:

char* cs = (char*) malloc(sizeof(str.c_str()));

因为sizeof(str.c_str())必然会给你一些像4或8这样的小数字(取决于你机器上指针的大小,str.c_str()的结果。

当然,它并不重要,因为下一行,你正在泄漏你刚才错误分配的内存:

cs = const_cast<char*> (str.c_str());

我远不相信你需要const_cast<char *>(这肯定是错误的,因为修改string内的字符串是未定义的行为。)

相关问题