Question

I'm using the following function to open a dialog box, using the OPENFILENAME. Problem is, after opening the dialog box, and closing it, everything works fine, but when I exit my application then Windows says it crashed.

bool openDialog()
{
  OPENFILENAME ofn;       // common dialog box structure
  char szFile[260];       // buffer for file name
  HWND hwnd = NULL;       // owner window
  HANDLE hf;              // file handle

  // Initialize OPENFILENAME
  ZeroMemory(&ofn, sizeof(ofn));
  ofn.lStructSize = sizeof(ofn);
  ofn.hwndOwner = hwnd;
  ofn.lpstrFile = szFile;
  //
  // Set lpstrFile[0] to '\0' so that GetOpenFileName does not 
  // use the contents of szFile to initialize itself.
  //

  ofn.lpstrFile[0] = '\0';
  ofn.nMaxFile = sizeof(szFile);
  ofn.lpstrTitle = "Open File";
  ofn.lpstrFilter = "Custom File\0*.Cus\0";

  ofn.nFilterIndex = 1;
  ofn.lpstrFileTitle = NULL;
  ofn.nMaxFileTitle = 0;
  ofn.lpstrInitialDir = NULL;
  ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

  // Display the Open dialog box. 

  if (GetOpenFileName(&ofn) == true) 
  {
    path = ofn.lpstrFile;
    return true;
  }
  else
  {
    return false;
  }
}

I noticed it was the dialog box because the crash only happens if I use it at runtime, meaning that when I close the application without opening the dialog box at some point, it exits successfully.

Anyways, as far as I researched, it is probably caused my a 'heap corruption' or something similar that I don't have much knowledge of, so when my application tries to close, it doesn't release memory as it should (?). If anyone could figure out a solution it'd be greatly appreciated.

Was it helpful?

Solution

Most likely the problem is to do with path if this is simply a const char * or char * declared outside the function.

When the openDialog function returns, both the ofn structure of type OPENFILENAME and character array szFile go out of scope (along with all the other local, stack-allocated variables) and are no longer valid. As a result, the character array that ofn.lpstrFile and consequently path point to is no longer valid.

You should allocate space for the file name outside the function and perform a copy with strcpy, strncpy or equivalent before returning from it. Another approach would be to move the szFile character array out of the function and into the containing class as a member variable. Either way, the scope of the character array containing the file name returned needs to extend beyond the lifetime of the execution of the openDialog function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top