Ustring error (during printing)

327 Views Asked by At

I want to parse UTF-8 file to ustring, I read this file in str. There is an error: terminate called after throwing an instance of 'Glib::ConvertError'. What should I do?

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

There are 1 best solutions below

0
On

This looks very wrong:

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

as sizeof(str.c_str()) is bound to give you some small number like 4 or 8 (whichever is the size of a pointer on your machine, as the result of str.c_str().

Of course, it doesn't REALLY matter, since the next line, you are leaking the memory you just allocated incorrectly:

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

I'm far from convinced that you need the const_cast<char *> (it is certainly WRONG to do this, since modifying the string inside a string is undefined behaviour).