Reputation: 1598
I have the following code
char *GetBytesString(char message[])
{
wchar_t utf16_str;
char *ptr;
mbstowcs(&utf16_str, message, sizeof(message));
ptr = (char *) malloc(sizeof(utf16_str) + 2);
memcpy(ptr, &utf16_str, sizeof(utf16_str));
return ptr;
}
Whenever I try to call it, I get an error saying that Heap corruption has occurred around utf16_str. What can I do to fix it?
Thanks!
Upvotes: 0
Views: 292
Reputation: 2625
It should have been wchar_t *utf16_str
instead of wchar_t utf16_str
. Refer the link for the examples from msdn for mbstowcs
.
Upvotes: 1
Reputation: 400029
Stop overwriting random memory.
This:
wchar_t utf16_str;
Only reserves space for one wide character, and then you write the entire converted string on top of that.
You should do the malloc()
first, but you need to use strlen()
to figure out how many characters are going to be needed. Then convert into the allocated buffer, and return that.
There are more issues, for instance sizeof message
doesn't work like you probably expect it to.
Also, please don't cast the return value of malloc()
in C.
Upvotes: 4