0

The problem is described in the title.

I have two functions. In the first I get file name (variable text), but the function does not return expected value. After returning the value text, it becomes an abrakadabra. But in the second function variable text is returned correctly. Any help would be greatly appreciated.

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;
}
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
renat2
  • 19
  • 1
  • 1
    `text = b;` points into the `_bstr_t` object, making it a dangling pointer once the `_bstr_t` object is destroyed. You will need to change your code to return some string object that manages its own memory (either `_bstr_t` or something else) – M.M Apr 22 '17 at 04:52

1 Answers1

2

The function returns a pointer text which is freed once the function returns, hence it is undefined behavior. You can use malloc to allocate memory for it on the heap but you also need to free it.

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

or for C++,

char* text = new char[text_size];

where text_size is the size of your string.

XZ6H
  • 1,779
  • 19
  • 25