Without having experience in Windows, I see that in your code reserves 1 byte at the end of the chain, to store the end of it.
LPWSTR str2 = (LPWSTR)malloc(wcslen(str1)+1);
DWORD size = wcslen(str1)+1;
However, you use L-strings, with wide characters. I do not remember the exact size or the concrete type (wchar_t or similar), but I think that Window used 32-bit characters (4 bytes) for that type of strings.
Try reserving 4 bytes, instead of one:
malloc( wcslen( str1 ) + 4 );
If I remember the exact type, I will edit the answer.
postdata: do not mix types. If you use wide strings, use wide characters; if you use normal strings
char * (LPSTR in Windows?), then use normal characters (sizeof (char))
It's wchar_t; therefore, the correct thing would be
LPWSTR str2 = (LPWSTR)malloc(wcslen(str1)+sizeof(wchar_t));
It's a common mistake to confuse bytes with characters .
malloc() works with bytes .
char *str = "hola"; is an array of characters that, coincidentally, have a size of 1 byte.
wchar_t *str2 = L"adios"; is an array of characters that does not have to be 1 byte each.
If it were possible to use
sizeof with memory blocks, we would have something like this:
sizeof( malloc( 100 ) ) -> 100
sizeof( "hola" ) -> 5 ( 4 caracteres de 1 byte, mas 1 caracter de terminador de la cadena.
sizeof( L"adios" ) -> depende de la arquitectura, el sistema, etc. Como se vió en el problema, puede ser perfectamente de 48 bytes ( 5 caracteres * 4 bytes cada uno, + 1 caracter (otros 4 bytes) de terminador de la cadena.
In addition to the above, the functions that work with strings are prepared and specialized in the type of strings they use. Therefore,
strcpy() adds 1 byte at the end, while
wcpcpy() adds a width character (4 or more bytes) at the end.
Conclusion : do not assume sizes, use the
sizeof (which is from the beginning of the language, for something will be), do not mix types, and use the appropriate functions for each one. p>