【问题标题】:Heap corruption while trying to free a wchar_t pointer尝试释放 wchar_t 指针时堆损坏
【发布时间】:2015-10-06 18:49:29
【问题描述】:

这是一个评估宽字符串是 L"false" 还是 L"true" 的代码,但是当我尝试运行它时,它在尝试释放重复的字符串指针“HEAP CORRUPTION DETECTED”时给了我这个错误: 在 Normal block(#135756) at 0x00000000002EB3A0 之后。CRT 检测到应用程序在堆缓冲区结束后写入内存。”。

这是内联代码:

const wchar_t* sequence = L"false";

wchar_t* duplicate;
size_t length = wcslen(sequence) + 1;

duplicate = static_cast<wchar_t*>(malloc(length));

wcscpy_s(duplicate, length, sequence);

int boolean = -1;

if (wcscmp(duplicate, L"false") == 0) {
    boolean = 0;
}
else if (wcscmp(duplicate, L"true") == 0) {
    boolean = 1;
}

free(duplicate);

在 free 语句之前,所有字符串指针似乎都正常。我确信我犯了一些严重的错误,仅仅是因为我能够破坏堆。

编译器:Microsoft Visual Studio 2015 RC

处理器:Inter Core i5-3450 3.10 GHz

【问题讨论】:

  • 什么是sizeof(wchar_t)

标签: c++ heap-corruption widechar


【解决方案1】:

使用

重复 = static_cast(malloc(length * sizeof(wchar_t));

否则你没有足够的空间容纳宽字符串

【讨论】:

  • 更好,length * sizeof duplicate[0]。更好的是,std::wstring
  • 没错,我怎么会这样......感谢您的快速回答。
猜你喜欢
  • 2011-08-21
  • 1970-01-01
  • 2015-08-14
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
  • 2017-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多