分配空终止符时Windows剪贴板函数崩溃



在我复制文本的函数中,我做了以下操作:

    // Allocate a global memory object for the text. 
    hglbCopy = GlobalAlloc(GMEM_MOVEABLE, 
        ((text.length() + 1) * sizeof(WCHAR))); 
    if (hglbCopy == NULL) 
    { 
        CloseClipboard(); 
        return; 
    } 
    // Lock the handle and copy the text to the buffer. 
    lptstrCopy = (LPWSTR)GlobalLock(hglbCopy); 
    memcpy(lptstrCopy, text.c_str(), 
        (text.length() + 1) * sizeof(WCHAR) ); 
    lptstrCopy[(text.length() + 1) * sizeof(WCHAR)] = (WCHAR) 0;    // null character CRASHES HERE
    GlobalUnlock(hglbCopy); 

当我复制一大块文本时,它在分配空终止符时崩溃。在计算分配多少内存时,我的数学是否有问题?

谢谢

您不必自己分配空终止符。

如果你想自己做,就像这样做:

((WCHAR*)lptstrCopy)[text.length()]=L'';

最新更新