【问题标题】:char to wchar_t results in heap corruptionchar 到 wchar_t 导致堆损坏
【发布时间】:2013-08-23 10:49:52
【问题描述】:

我有以下代码

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

标签: c malloc heap-memory


【解决方案1】:

停止覆盖随机内存。

这个:

wchar_t utf16_str;

只为 一个 宽字符保留空间,然后将整个转换后的字符串写在上面。

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

还有更多问题,例如 sizeof message 无法像您预期的那样工作。

另外,please don't cast the return value of malloc() in C。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 2013-04-15
      • 2021-11-10
      相关资源
      最近更新 更多