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);
#else
SetClipboardData(CF_TEXT, hClipboardData);
#endif
GlobalUnlock(hClipboardData);
CloseClipboard();
}
Data in the list box:
John Smith 1978
Angelina 1975
Brad Pitt 1950
source
share