1

I'm trying to use memcpy to convert a TCHAR array into a BYTE array but the memcpy function is only copying 1 TCHAR from the tchar array into the byte array.

I have no idea why this is happening.

Here is a code snippet.

TCHAR test[] = L"This is a test string, its purpose is to do some testing!";
DWORD testSizeBytes = sizeof(TCHAR) * lstrlen(test);
LPBYTE byteArray = new BYTE[testSizeBytes+1];
memcpy(byteArray,test,testSizeBytes);

If I used this snippet the byteArray would just contain 'T';

Any help would be appreciated.

EDIT: I fixed the issue (It was a typo). The code I wrote here works flawlessly. My compiler is in a windows VM so I had to retype it here and unknowingly fixed the typo.

  • For a good discussion on this if you're interested, have a look at http://stackoverflow.com/questions/4707012/c-memcpy-vs-stdcopy – MrDuk Apr 19 '14 at 04:11
  • How are you determining that only one TCHAR is copied? – Benjamin Lindley Apr 19 '14 at 04:14
  • I'm trying to avoid using anything I'll need to access via std:: – OrangeMotto Apr 19 '14 at 04:14
  • I'm determinating that only one is copied using the debugger and breakpoints. – OrangeMotto Apr 19 '14 at 04:14
  • Does `testSizeBytes` have the right value? – imreal Apr 19 '14 at 04:16
  • 1
    I suspect your debugger is only displaying the first character because that's all you have a pointer to, it doesn't know that you expect it to be a string. Have you tried examining the subsequent memory? – ajshort Apr 19 '14 at 04:17
  • Write some code that actually outputs stuff based on this; that is more reliable than what the debugger says. – M.M Apr 19 '14 at 04:19
  • testSizeBytes has the value of 114 for that string. My compilar normally shows the whole array. When the array is first allocated it shows the full array will of empty chars. The 1 char size is further confired by length Errors with CryptEncrypt further on. – OrangeMotto Apr 19 '14 at 04:24

2 Answers2

3
TCHAR test[] = L"This is a test string, its purpose is to do some testing!";

This is a wide character (wchar_t) string. On Windows, with UNICODE defined, that is UTF-16. In UTF-16, the character 'T' is 2 bytes. The first byte corresponds to the ASCII value of 'T' (decimal 84). The second byte is a 0. So when you copy this over to your byte array, it looks like a null terminated c-string with 1 character. The other characters are there, but they come after the end of the apparent c-string, so your debugger is apparently ignoring them.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
0

As the comment from ajshort mentioned, your debugger probably does not realize you are dealing with an array.

If you can use your debugger to look at memory, try to look at the memory location byteArray + 1 and byteArray + 2, etc.

I am not on Windows, so I cannot tell you how to do that, but the equivalent gdb command would be x byteArray + 1.

merlin2011
  • 71,677
  • 44
  • 195
  • 329