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;
This code works fine adding text to the control until the string becomes around 20 characters long in which the program crashes. Stepping through the program, it crashes where I allocate memory for the lpNewText buffer. I don’t know what’s wrong. Visual Studio takes me to the malloc.h header when it crashes.
For a start I’d recommend that you abandon
mallocand use C++ memory allocation techniques. Likenew,new[],std::vector<>,std::string,std::wstringetc.That said, I can see the following errors in your code:
I don’t really know what your code is trying to do so I’m not going to try to re-write it and correct everything. The fundamental problem you have is that you systematically write sizeof(…) and calculate the size of a pointer when you actually want the size of a character element.
Perhaps what you really need to do is throw away all this horrid code and use
std::wstringto do your concatenation.