-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 に答える