我有以下代码
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 周围发生了堆损坏。我该怎么做才能修复它?
谢谢!
最佳答案
停止覆盖随机内存。
这个:
wchar_t utf16_str;
只为一个宽字符保留空间,然后将整个转换后的字符串写在上面。
您应该先执行 malloc()
,但您需要使用 strlen()
来确定需要多少个字符。然后转换为分配的缓冲区,并返回。
还有更多问题,例如 sizeof message
没有像您预期的那样工作。
关于char 到 wchar_t 导致堆损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18400996/