Reputation: 1583
I have the following code and it works well :
int Size ;
CString Message ;
BYTE Buffer[256] ;
Message = _T("Some Text") ;
Size = Message.GetLength() * sizeof(WCHAR) ;
memcpy(Buffer,&Message,Size) ;
But when i change it to this :
int Size ;
CString Message ;
BYTE* Buffer ;
Buffer = (BYTE*) malloc(256) ;
Message = _T("Some Text") ;
Size = Message.GetLength() * sizeof(WCHAR) ;
memcpy(Buffer,&Message,Size) ;
And then check the Buffer data, it populated with some random trash bytes
What's wrong ?
Upvotes: 1
Views: 1458
Reputation: 35891
BYTE Buffer[256]
creates an array of 256 BYTE
-sized elements, regardless of BYTE
's size.
malloc(256)
on the other hand allocates 256 bytes of memory. Try malloc(256 * sizeof(BYTE))
.
Upvotes: 3
Reputation: 393134
CString is not a POD type and cannot be bitwise copied.
It seems you have to switch paradigms from C to C++
From the docs it seems like http://msdn.microsoft.com/en-us/library/aa300569(v=vs.60).aspx supports a conversion:
LPCTSTR raw = (LPCTSTR) Message;
// now memcpy from `raw`
Upvotes: 4