Correct usage of Mbstowcs

I got this snippet of code from a security website. I thought I would post it, since its a common mistake most do. Not allocating enough memory when using buffers:
Examples of Incorrect Code:
wchar_t destString[20];
const char sourceString[] = “Pretend this string is multi-byte.”;
// The following has multiple problems:
// 1. The number of characters destString can hold is actually sizeof(destString)/sizeof(destString[0])
// 2. The buffer is not large enough to hold the converted string.
// 3. No check is done to ensure that the entire string was converted.
mbstowcs(destString, sourceString, sizeof(destString));
Examples of Corrected Code
const char sourceString[] = “Pretend this string is multi-byte.”;
// Size the output buffer as needed to fit the complete result
int charsToProduce = mbstowcs(NULL, sourceString, 0) + 1; // note error return of -1 is possible
if (charsToProduce == 0) { /* handle error */ }
if (charsToProduce > ULONG_MAX/sizeof(wchar_t)) return error;
wchar_t *destString = (wchar_t *)malloc( charsToProduce * sizeof(wchar_t) );
mbstowcs(destString, sourceString, charsToProduce);

Leave a Reply

Your email address will not be published. Required fields are marked *