视觉工作室 2010
当我为 char 字符串分配内存,将字符串(指针)传递给函数,然后尝试释放内存时,我收到“检测到堆损坏”运行时错误。
我怀疑这是函数在返回后将内存标记为“已释放”的结果,但我仍然对如何解决这个问题感到困惑。简单地删除对 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)
{
...
}