2013-08-23 43 views
0

我有以下代码的char wchar_t的结果堆损坏

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; 
} 

每当我尝试调用它,我得到一个错误说,堆腐败各地utf16_str发生。我能做些什么来解决它?

谢谢!

+1

它应该是wchar_t * utf16_str –

回答

4

停止覆盖随机存储器。

此:

wchar_t utf16_str; 

只保留了一个字符空间,然后你写最重要的是整个转换后的字符串。

您应该首先执行malloc(),但您需要使用strlen()来确定需要多少个字符。然后转换成分配的缓冲区,然后返回。

还有更多的问题,例如sizeof message不像你可能期望的那样工作。另外,please don't cast the return value of malloc() in C

1

它应该是wchar_t *utf16_str而不是wchar_t utf16_str。请参阅link以获取msdn的示例,以获取mbstowcs