c++ - 函数返回错误值,而函数内部的逐步调试似乎没问题

标签 c++

<分区>

标题中描述了问题。

我有两个功能。首先我得到文件名(变量 text),但该函数没有返回预期值。返回值 text 后,它变成了 abrakadabra。但是在第二个函数中变量 text 被正确返回。任何帮助将不胜感激。

char* GetCurrentClipboardData(...)
{
    char* text;
    wchar_t file[MAX_PATH];

    if( OpenClipboard(NULL) )
    {   
        HGLOBAL hFile = (HGLOBAL)GetClipboardData(CF_HDROP);
        if (hFile)
        {
            HDROP hDrop = (HDROP)GlobalLock(hFile);
            DragQueryFile(hDrop, 0, file, MAX_PATH);
            _bstr_t b(file);
            text = b;
            if (text != Text)
            {
                SaveDataToFile (file_path, current_time, text);
                char* copy = ReadFile(shadowcopy_path);
                if (copy == "1")
                    MakeFileShadowCopy(file, shadowcopies);
            }
            GlobalUnlock(hFile);
        }

        HBITMAP hBitmap = (HBITMAP)GetClipboardData(CF_BITMAP);
        if (hBitmap)
        {
            text = "Изображение";
            if (text != Text)
            {
                SaveDataToFile (image_path, current_time, text);
                char* copy = ReadFile(shadowcopy_path);
                if (copy == "1")
                    MakeImageShadowCopy(hBitmap, shadowcopies, current_date, current_time);
            }
            GlobalUnlock(hBitmap);
        }
        CloseClipboard();
    }
    return text;
}

最佳答案

该函数返回一个指针 text,一旦函数返回,该指针就会被释放,因此它是未定义的行为。您可以使用 malloc 在堆上为其分配内存,但您还需要释放它。

char* text;
text = (char*)malloc(text_size * sizeof(char));

或者对于 C++,

char* text = new char[text_size];

其中 text_size 是字符串的大小。

关于c++ - 函数返回错误值,而函数内部的逐步调试似乎没问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43554630/

相关文章:

c++ - debian box 中 c++ 应用程序的性能不一致

c++ - 在另一个结构中初始化一个结构数组

C++/Win32 : Keyboard input to a non-foreground window

c++ - 如何在保持文档打开的同时关闭 MFC CVIEW

c++ - C ReadProcessMemory - 如何检查与进程关联的内存区域

c++ - 将 PDF 打印到 HDC(MFC 设备上下文)

c++ - 使用 unordered_map 移动构造函数

c++ - Eclipse CDT 无法解析 STL 容器中元素的方法

c++ - 为什么使用 boost::none 无法通过 nvcc 编译?

c++ - 可能是C中的指针问题