尝试释放 wchar_t 指针时堆损坏

Heap corruption while trying to free a wchar_t pointer

这是一个评估宽字符串是 L"false" 还是 L"true" 的代码,但是当我尝试 运行 它时,它在尝试时给我这个错误释放重复的字符串指针 "HEAP CORRUPTION DETECTED: after Normal block(#135756) at 0x00000000002EB3A0. CRT detected that the application wrote to memory after end of heap buffer.".

这是内联代码:

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 语句之前,所有字符串指针似乎都正常。我确信我犯了一些严重的错误,仅仅是因为我能够破坏堆。

编译器:微软Visual Studio 2015 RC

处理器:Inter Core i5-3450 3.10 GHz

使用

duplicate = static_cast(malloc(length * sizeof(wchar_t));

否则你对宽字符串 space 的理解不够