-1
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 标头。

4

1 回答 1

3

首先,我建议您放弃malloc并使用 C++ 内存分配技术。比如new, new[], 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用来做你的连接。

于 2012-12-09T21:25:58.567 回答