0

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!

trincot
  • 317,000
  • 35
  • 244
  • 286
dreadiscool
  • 1,598
  • 3
  • 18
  • 31

2 Answers2

4

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.

Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606
1

It should have been wchar_t *utf16_str instead of wchar_t utf16_str. Refer the link for the examples from msdn for mbstowcs .

Santhosh Pai
  • 2,535
  • 8
  • 28
  • 49