-1

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!

A.S.H
  • 29,101
  • 5
  • 23
  • 50
Vess
  • 249
  • 1
  • 3
  • 10
  • 2
    Maybe the console you're printing it to doesn't support these characters. – selalerer Dec 08 '16 at 09:46
  • But on that times when it prints garbage it returns for wcslen(buf) some enromous number insted of 90 it returns for exmplae 620, and in debugger I can see that first 90 wchars are from my string, and after that it is garbage – Vess Dec 08 '16 at 10:04
  • 2
    `(const WCHAR*)buf+ L'\0'` does not append a terminating zero – Lyth Dec 08 '16 at 10:16
  • @Vess yes, there is wcsncpy (similar to strncpy) – Lyth Dec 08 '16 at 10:21
  • Either the end of the string is marked with a terminator or it's not. If it's marked, there's no reason to try to add a zero character to it. If it's not marked, you need to pass the length to the function that marks the end with a zero character or it has no way to know where to mark. So aside from `+` not doing what you want, you don't use the length in a case where all you have to tell you what to use *is* the length! – David Schwartz Dec 08 '16 at 10:32

1 Answers1

1

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.

Lyth
  • 2,171
  • 2
  • 29
  • 37