看似小的请求后,malloc调用失败

时间:2012-12-09 21:12:01

标签: c++ winapi malloc

void StaticControl::addText(LPWSTR text)
{
    lpCurrentText = (LPWSTR)malloc((GetWindowTextLength(hStatic) + 1) * sizeof(LPWSTR));
    GetWindowText(hStatic, lpCurrentText, GetWindowTextLength(hStatic) + 1);

    lpInput = text;
    chInput = (char*)malloc(sizeof (lpInput) *sizeof(LPWSTR)/sizeof(char*));
    chCurrent = (char*)malloc(sizeof (lpCurrentText) *sizeof(LPWSTR)/sizeof(char*));
    wcstombs(chCurrent, lpCurrentText, wcslen(lpCurrentText) + 1);
    wcstombs(chInput, lpInput, wcslen(lpInput) + 1);
    strcat(chCurrent, chInput);
    lpNewText = (LPWSTR)malloc(strlen(chCurrent) * sizeof(char*)); //this is where it crashes
    mbstowcs(lpNewText, chCurrent, strlen(chCurrent) + 1);
    SetWindowText(hStatic, lpNewText);
    return;
}
//where
HWND hStatic;
LPWSTR lpCurrentText;
LPWSTR lpInput;
LPWSTR lpNewText;
char*  chInput;
char*  chCurrent;

此代码可以很好地向控件添加文本,直到字符串变为大约20个字符长的程序崩溃。逐步执行该程序,它崩溃了我为lpNewText缓冲区分配内存的地方。我不知道出了什么问题。当它崩溃时,Visual Studio会将我带到malloc.h标题。

1 个答案:

答案 0 :(得分:3)

首先,我建议您放弃malloc并使用C ++内存分配技术。与newnew[]std::vector<>std::stringstd::wstring等相同。

也就是说,我可以在您的代码中看到以下错误:

lpCurrentText = (LPWSTR)malloc((GetWindowTextLength(hStatic) + 1) * sizeof(LPWSTR));
// should be sizeof(*lpCurrentText), i.e. size of a wide char 
// and not size of a pointer as you have it

chInput = (char*)malloc(sizeof (lpInput) *sizeof(LPWSTR)/sizeof(char*));
// sizeof(lpInput), sizeof(LPWSTR) and sizeof(char*) are all equal to the
// same thing, the size of a pointer

chCurrent = (char*)malloc(sizeof (lpCurrentText) *sizeof(LPWSTR)/sizeof(char*));
// as above

lpNewText = (LPWSTR)malloc(strlen(chCurrent) * sizeof(char*)); 
// sizeof(char*) is the size of a pointer, not what you want

return;
// rather pointless when the return type is void

我真的不知道你的代码试图做什么,所以我不打算重新编写它并纠正一切。您遇到的根本问题是,当您真正想要字符元素的大小时,系统地编写sizeof(...)并计算指针的大小。

也许您真正需要做的就是抛弃所有这些可怕的代码并使用std::wstring进行连接。