Visual Studio 2010
When I allocate memory for a char string, pass the string (pointer) to a function, then try to free the memory, I get a "Heap Corruption Detected" run-time error.
I suspect this is a result of the function marking the memory as "freed" once it returns, but I am still puzzled as how to get around this. I do not feel comfortable simply removing the call to free().
// this function takes a char string, converts it to a wide char string,
// then passes the converted string to another function.
void Class::WriteToLog(const char * msg)
{
// allocate memory
wchar_t * wMsg = (wchar_t*)malloc((strlen(msg) * sizeof(wchar_t)) + 1); // add one for null terminating char
// convert to wide char. This works fine, and returns 4 when msg is 4 chars long.
numChar = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, msg, strlen(msg), wMsg, strlen(msg));
wMsg[numChar] = L'\0'; // terminate string
// At this point wMsg contains the same thing msg contains. Works fine.
WriteToLogW(wMsg); // Works fine. Writes the string to a text file.
free(wMsg); // Heap Corruption Detected
}
void Class::WriteToLogW(const wchar_t * msg)
{
...
}