Auto truncate and zero terminate the string buffer in buffer overflow

I have the following code that can load text from all child windows of the specified parent window. It works fine, but sometimes there are some parent windows (for example, open notebooks with a very long C ++ source file) that have a lot of text and cause a buffer overflow.

BOOL CALLBACK EnumChildProc(__in HWND hWnd, __in LPARAM lParam) {

    LRESULT TEXT_LENGTH = NULL;
    WCHAR szText[32767];
    LPWSTR szWindowText;
    UINT nBuffer = NULL, nText = NULL;

    szWindowText = reinterpret_cast<LPWSTR>(lParam); szText[0] = L'\0';
    nBuffer = (UINT)wcslen(szWindowText);
    TEXT_LENGTH = SendMessage(hWnd, WM_GETTEXTLENGTH, NULL, NULL);

    if (TEXT_LENGTH > NULL)
    {
        SendMessage(hWnd, WM_GETTEXT, (WPARAM)32767, reinterpret_cast<LPARAM>(&szText));
        szText[TEXT_LENGTH] = L'\n'; szText[TEXT_LENGTH + 1] = L'\0';

        while ((nBuffer < 32766) && (szText[nText] != L'\0'))
        { szWindowText[nBuffer++] = szText[nText++]; }

        szWindowText[nBuffer] = L'\0';
    }
    return TRUE;
}

The line SendMessage(hWnd, WM_GETTEXT, (WPARAM)32767, reinterpret_cast<LPARAM>(&szText));sometimes causes a buffer overflow and my application crashes.

I know how to detect this overflow like if (TEXT_LENGTH > 32767), but I cannot dynamically increase the size of the buffer szText.

, , 32767 ( TEXT_LENGTH 32767) szWindowText .

.

+4
3

:

  • TEXT_LENGTH. (+1 '\ 0')
  • szText WM_GETTEXT, ,
  • char, SendMessageA, wchar_t SendMessageW. SendMessage - , wchar_t char . TCHAR SendMessage, .

DWORD l = SendMessage(hWnd, WM_GETTEXTLENGTH, NULL, NULL);

if (l > 0){
   TCHAR *szText = new TCHAR[l + 1];
   SendMessage(hWnd, WM_GETTEXT, (WPARAM)l + 1, reinterpret_cast<LPARAM>(szText));

  // use szText

   delete[] szText;
}
0

, \n, , - sizeof szText-1 32767 WM_GETTEXT.

NB Simonyi, , . szText, WM_GETTEXT.

+1

SendMessage(hWnd, WM_GETTEXT, (WPARAM)32767, reinterpret_cast<LPARAM>(&szText)); , . .

Your real problem is that you are adding characters to the pointer supplied as lParamwithout knowing the size of the destination buffer. You must specify the size of the delivery destination buffer.

0
source

Source: https://habr.com/ru/post/1683335/


All Articles