Reputation: 3326
I'm pretty new to C++ and have run into a problem which I have not been able to solve. I'm trying to convert a System::String to a wchar_t pointer that I can keep for longer than the scope of the function. Once I'm finished with it, I want to clean it up properly. Here is my code:
static wchar_t* g_msg;
void TestConvert()
{
pin_ptr<const wchar_t> wchptr = PtrToStringChars("Test");
g_msg = (wchar_t*)realloc(g_msg, wcslen(wchptr) + 1);
wcscpy(g_msg, wchptr);
free (g_msg); // Will be called from a different method
}
When the free is called, I'm getting "HEAP CORRUPTION DETECTED: after Normal block (#137) at 0x02198F90."
Why would I be getting this error?
Andrew L
Upvotes: 1
Views: 2941
Reputation: 5176
I think the you're allocating too small memory block for the string. Each character takes 2 bytes (in MSVC) because it's a wide string:
g_msg = (wchar_t*)realloc(g_msg, (wcslen(wchptr) + 1)*sizeof(wchar_t));
Upvotes: 5
Reputation: 146968
System::String is a managed string class, not a C++ string class. You need to convert to a std::wstring, which manages it's own memory, not a const wchar_t*.
Upvotes: 0