0

视觉工作室 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)
{
    ...
}
4

2 回答 2

2

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

由于您使用的是wchar_t,所以空终止符将占用sizeof(wchar_t)字节,这实际上总是大于 1。因此,malloc调用分配的内存不足。重新构造您的malloc调用,使其如下所示:

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

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

于 2014-01-30T22:24:59.853 回答
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));
于 2014-01-30T22:25:09.397 回答