将指针传递给函数然后在指针上调用free()时,“检测到堆腐败”

时间:2014-01-30 22:21:15

标签: c++ malloc free char-pointer

Visual Studio 2010

当我为char字符串分配内存时,将字符串(指针)传递给函数,然后尝试释放内存,我得到“Heap Corruption Detected”运行时错误。< / p>

怀疑这是该函数在返回后将内存标记为“已释放”的结果,但我仍然对如何解决这个问题感到困惑。只是删除对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)
{
    ...
}

2 个答案:

答案 0 :(得分:2)

您在+1末尾添加的malloc只会在使用char时为空终结符分配足够的内存,因为char是1个字节(因此空终止符将占用一个字节)。

由于您正在使用wchar_t,因此空终止符将占用sizeof(wchar_t)个字节,这几乎总是大于1.因此,malloc调用分配的内存不足。将您的malloc电话重新构建为如下所示:

wchar_t * wMsg = (wchar_t*) malloc((strlen(msg) + 1) * (sizeof(wchar_t));

这样,分配的总字节数为空终止符留出了空间。

答案 1 :(得分:2)

即使是宽字符串的终止nul也很宽,所以只给它一个字节是不够的。变化:

wchar_t * wMsg = (wchar_t*)malloc((strlen(msg) * sizeof(wchar_t)) + 1);

wchar_t * wMsg = (wchar_t*)malloc((strlen(msg) + 1) * sizeof(wchar_t));