malloc调用在一个看似很小的请求后失败

malloc call fails after a seemingly small request

本文关键字:请求 失败 一个 调用 malloc      更新时间:2023-10-16
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缓冲区分配内存的地方崩溃。我不知道怎么了。当malloc.h标头崩溃时,VisualStudio会带我进入它。

首先,我建议您放弃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来进行连接。