0

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;
ST3
  • 8,826
  • 3
  • 68
  • 92
  • According to this page: https://developer.gnome.org/glibmm/2.34/classGlib_1_1ConvertError.html the converterror contains some extra information about "what is wrong", which may be helpful in determining what is the ACTUAL cause of error. – Mats Petersson Jul 12 '13 at 11:20

1 Answers1

1

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).

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227