This is a code that evaluates if a wide string is either L"false" or L"true", but when I try to run it, it gives me this error when trying to free the duplicate string pointer "HEAP CORRUPTION DETECTED: after Normal block(#135756) at 0x00000000002EB3A0. CRT detected that the application wrote to memory after end of heap buffer.".
Here is the inline code:
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);
All the string pointers seem to be OK right before the free statement. I am sure I have done some serious mistake simply because I was able to corrupt the heap.
Compiler: Microsoft Visual Studio 2015 RC
Processor: Inter Core i5-3450 3.10 GHz
Use
duplicate = static_cast(malloc(length * sizeof(wchar_t));
otherwise you do not hane enough space for the wide string