1

I'm currently creating a class for a more comfortable use of GetOpenFileName. And now, I've encountered a problem:

I've included a string to set as the window title as a constructor argument. But when using it, the window just outputs lots of special characters.

This is my code:

OpenFileDialog(HWND hwndOwner = NULL, std::string WindowTitle = "", std::string FilterDescription = "Text Files", std::string FilterExtension = "txt", bool ShowAnyFilesOption = true) {
    ZeroMemory(&filename, sizeof(filename));
    ZeroMemory(&ofn, sizeof(ofn));
    ofn.lStructSize = sizeof(ofn);
    ofn.hwndOwner = hwndOwner;
    setFilter(FilterDescription, FilterExtension, ShowAnyFilesOption);
    ofn.lpstrFile = filename;
    ofn.nMaxFile = MAX_PATH;
    ofn.lpstrTitle = WindowTitle.c_str();
    ofn.Flags = OFN_DONTADDTORECENT | OFN_FILEMUSTEXIST;
}


bool setFilter(std::string FormatDescription, std::string FileExtension, bool ShowAnyFilesOption = true) {
    if (FileExtension != "") {
#define NULLstr sFilter.push_back('\0')

        sFilter = FormatDescription + " (*." + FileExtension + ")";
        NULLstr;
        sFilter.append("*." + FileExtension);
        NULLstr;

        if (ShowAnyFilesOption) {
            sFilter.append("Any Files (*.*)");
            NULLstr;
            sFilter.append("*.*");
            NULLstr;
        }
        ofn.lpstrFilter = sFilter.c_str();
        return true;
#undef NULLstr
    }

    else // File extension empty
                return false;
}

I would be very happy if you could help me solve this problem. I'm not very good at using the WinAPI, to be honest

  • I think this line: `ofn.lpstrTitle = WindowTitle.c_str();` (and the similar one in the `setFilter` function) is assigning a 'dangling pointer' as the title. (The underlying `string` goes out of scope once the function to which it is passed returns.) – Adrian Mole Nov 21 '19 at 22:04
  • `Ì` is 0xCC in [Windows-1252](https://en.wikipedia.org/wiki/Windows-1252) which is the value for [uninitialized memory in debug mode](https://stackoverflow.com/q/370195/995714). When you see a series of bytes of special values, convert them to hex and see – phuclv Nov 22 '19 at 01:48

1 Answers1

2

Since GetOpenFileName call isn't happening inside OpenFileDialog constructor, you want to copy your string into a more persistent location (such as a class field inside OpenFileDialog)- an std::string that you passed as an argument may get freed up later and used for something else, thus causing your c_str to point at unrelated/garbage data.

YellowAfterlife
  • 2,967
  • 1
  • 16
  • 24