Search code examples
c++cprintfgarbagewchar

Problems with wchar* and printing it C


I have a problem, sometimes in the end of string I get many ????????? I don't know how to fix this, not to get that garbage. . .

USHORT length = (USHORT)d.GetLength();
if (length == 0) {
    cEncodeJsonUtil->AddElement(dataHeader, L"null", false);
}
else {
    WCHAR* buf = (WCHAR*)d.GetData();
    //buf[length + 1] = L'\0'; //bugs like this as well as like buf[length]=L'\0';
    // should I escape here or not ? is this + L'\0' ok ?S?!? Even after excaping still there is trash inside.
    cEncodeJsonUtil->AddElement(dataHeader, (const WCHAR*)buf+ L'\0');
}

cEncodeJson->AddElement just prints out element like this

    wprintf(L"\n\"%s\" : \"%s\"\n", pwszKey, pwszValue);

Am I doing something wrong? Printing wrong? Should I maybe use:

swprintf(buf, L"%ls", buff); //to copy from the value I get to my own buffer?

Thanks a lot!


Solution

  • You were on the right track with this:

        WCHAR* buf = (WCHAR*)d.GetData();
        buf[length + 1] = L'\0';
    

    The nuance is that when you get a pointer to the data (without copying), you're still operating on the buffer in d. When d gets out of scope, it is destroyed (presumably with the data), so you may as well get any garbage.

    That is where wcsncpy can help to copy the data into another buffer that you control separately, add the terminating zero and pass it to AddElement. And always check carefully, if you accidentally store a pointer to data that is going to be destroyed.