Heap corruption during SetClipboardData ()

I am not sure what is the main reason for getting such an error (Heap Corruption) from the code below. When I look at the program, the TCHAR value is correctly allocated and copied to the clipboard data. However, it crashes when it goes to SetClipboardData (...).

Can any guru reveal a mistake?

Thanks in advance.

Error dialog:

The heap block in 04A781C0, changed to 04A78282, the last requested size ba of Windows caused a breakpoint in V4.exe.

This may be due to a bunch of corruption, which indicates an error in V4.exe or any of the downloaded dll files.

It may also be due to the user pressing F12, while V4.exe has focus.

The output window may contain more diagnostic information. The program '[10840] V4.exe: "Native" exited with code 0 (0x0).

the code:

    int nCount = m_ListBox.GetCount();
    CString szTemp, szText;
    for(int i=0; i<nCount; i++)
    {
        m_ListBox.GetText(i, szTemp);
        szText = szText + _T("\n") + szTemp;
    }
    if(OpenClipboard())
    {
        EmptyClipboard();
        HGLOBAL hClipboardData;
        size_t size = (szText.GetLength()+1) * sizeof(TCHAR);
        hClipboardData = GlobalAlloc(NULL, size);
        TCHAR* pchData = (TCHAR*)GlobalLock(hClipboardData);
        _tcscpy_s(pchData, size, LPCTSTR(szText));
#ifdef _UNICODE
        SetClipboardData(CF_UNICODETEXT, hClipboardData);  //--> crash here
#else
        SetClipboardData(CF_TEXT, hClipboardData);
#endif
        GlobalUnlock(hClipboardData);
        CloseClipboard();
    }

Data in the list box:

John Smith  1978  
Angelina    1975  
Brad Pitt   1950  
+3
source share
3 answers
_tcscpy_s (pchData, size, LPCTSTR (szText)); 

For the Unicode function wcscpy_s, the size parameter is the size in words, and you pass the size in bytes. This can lead to memory corruption as wcscpy_s fills the entire 0xFD buffer before copying to catch such errors. (thanks sharptooth for the exact info).

+5
source

Below is a quote from MSDN for SetClipboardData:

OpenClipboard hwnd NULL, EmptyClipboard NULL; SetClipboardData.

NULL OpenClipboard, SetClipboardData .

0

GlobalUnlock(hClipboardData); SetClipboardData(CF_UNICODETEXT, hClipboardData);

0
source

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


All Articles