Ustring错误(打印期间)

Ustring error (during printing)

本文关键字:打印 错误 Ustring      更新时间:2023-10-16

我想解析UTF-8文件到ustring,我在str中读取了这个文件。出现错误:在引发"Glib::ConvertError"的实例后调用了terminate。我该怎么办?

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;

这看起来非常错误:

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中的字符串是未定义的行为)。