Warning C6276

Cast between semantically different string types. Use of invalid string can lead to undefined behavior.

This warning indicates a potentially incorrect cast from a narrow character string (char*) to a wide character string (wchar_t*).

Remarks

Because the Microsoft compiler implements wide strings with a character size of 2 bytes, casting from a narrow string might produce strings that aren't correctly terminated. If you use such strings with the wcs* functions in the runtime library, they could cause buffer overruns and access violations.

Code analysis name: CHAR_TO_WCHAR_CAST

Example

The following code generates warning C6276. It's caused by an improper cast of the narrow string "a" (2 bytes, one for the 'a' and one for the null terminator) to a wide string (a 2-byte wide character 'a' with no null terminator):

#include <windows.h>

void f()
{
    WCHAR szBuffer[8];
    LPWSTR pSrc;
    pSrc = (LPWSTR)"a";
    wcscpy_s(szBuffer, pSrc);
}

The following code corrects this warning. It removes the problem cast and adds an L prefix to the string to define it as a properly terminated wide character string:

#include <windows.h>

void f()
{
    WCHAR szBuffer[8];
    LPWSTR pSrc;
    pSrc = L"a";
    wcscpy_s(szBuffer, pSrc);
}