gpt4 book ai didi

c++ - SetClipboardData() 期间的堆损坏

转载 作者:太空狗 更新时间:2023-10-29 20:48:14 27 4
gpt4 key购买 nike

我不确定从下面的代码中得到这样的错误(堆损坏)的根本原因是什么。当我单步执行程序时,TCHAR 值被正确分配并复制到剪贴板数据。但是,当它继续执行 SetClipboardData(...) 时崩溃。

有哪位大师可以帮助发现错误吗?

提前致谢。

错误对话框:

Heap block at 04A781C0 modified at 04A78282 past requested size of ba Windows has triggered a breakpoint in V4.exe.

This may be due to a corruption of the heap, which indicates a bug in V4.exe or any of the DLLs it has loaded.

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

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

代码:

    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();
}

列表框数据:

John Smith  1978  
Angelina 1975
Brad Pitt 1950

最佳答案

_tcscpy_s(pchData, size, LPCTSTR(szText)); 

对于 Unicode wcscpy_s 函数,size 参数是以字为单位的大小,而您以字节为单位传递大小。这可能会导致内存损坏,因为 wcscpy_s 在复制之前用 0xFD 填充所有缓冲区,以便捕获此类错误。(感谢 sharptooth 提供准确信息)。

关于c++ - SetClipboardData() 期间的堆损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3715729/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com