Why does printing this wide character string crash on windows?

Viewed 196

I stumbled upon a problem while going through some unit tests, and I am not entirely sure why the following simple example crashes on the line with sprintf (Using Windows with Visual Studio 2019).

#include <stdio.h>
#include <locale.h>

int main()
{
    setlocale(LC_ALL, "en_US.utf8");
    char output[255];
    sprintf(output, "simple %ls text", L"\u00df\U0001d10b");
    return 0;
}

Is there something wrong with the code?

1 Answers

char is 8-bit and wchar_t is 16-bit. When you try to convert the two, you will have to use functions like MultiByteToWideChar to convert between the two.

When you try to use Unicode strings in a multi-byte function, it causes buffer overflow, which might be the cause of your crashes.

Try using swprintf_s instead.

Related