Here is a C code that converts a wchar_t* string into a char* string :
wchar_t *myXML = L"<test/>";
size_t length;
char *charString;
size_t i;
length = wcslen(myXML);
charString = (char *)malloc(length);
wcstombs_s(&i, charString, length, myXML, length);
The code compiles but at exectution it detects a fatal error at the last line and stops running.
Now, if I replace the last line with this one :
wcstombs_s(&i, charString, length+1, myXML, length);
I just added +1 to the third argument. Then it works perfectly…
Why is there a need to add this trick ? Or is there a flaw elsewhere in my code ?
The trick is that you should always look for code of the form:
very suspiciously, because both
wcslen(3)andstrlen(3)return the string length without the nul byte, andmalloc(3)must allocate the space with that byte. C kinda sucks sometimes.So every time you see
string = malloc(len);rather thanstring = malloc(len+1);, be very careful to read howlengets assigned.Ought to do the trick. 🙂
EDIT:
Better would be to ask
wcstombs()for the size to allocate in the first place:The
+1allocates for the ascii nul, andwcstombs()will report how much memory is required to do the conversion. It’ll do the conversion twice, once to keep track of the memory required, and then once to store the result, but it will be MUCH simpler to maintain. The second time, when it stores the result, it will write at mostlenbytes including the ascii nul.