Question

I have a simple save file dialog that I wish to use as a tool to return the file path, name, and extension. This function produces a runtime error, saying that the stack around filename is corrupted. I wish to use it like so:

wchar_t filename[] = L"";
newGradebookDialog( hwnd, filename );

And here is my function. It modifies filename as I expect it to, but the runtime stack error is what I don't get.

void newGradebookDialog( HWND hwnd, wchar_t file[] )
{
 OPENFILENAME ofn;

 wchar_t saveFileName[MAX_PATH] = L"";

 ZeroMemory( &ofn, sizeof( ofn ) );

 ofn.lStructSize = sizeof(OPENFILENAME);
 ofn.hwndOwner = hwnd;
 ofn.lpstrFilter = L"Database File (*.db)\0*.db\0";
 ofn.lpstrFile = saveFileName;
 ofn.nMaxFile = MAX_PATH;
 ofn.lpstrDefExt = L"db";
 ofn.Flags  = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;
 ofn.lpstrTitle = L"Save New Database";

 if(GetSaveFileName(&ofn))
  wcscpy(file,saveFileName);
}
Was it helpful?

Solution

 wchar_t filename[] = L"";

That's an array with one element. You are copying a much bigger string into it, that corrupts the stack frame. Fix:

 wchar_t filename[MAX_PATH] = {0};

OTHER TIPS

I have a feeling that you corrupt memory via wcscpy -- you have allocated empty "filename" and copy the non-empty value (from saveFileName) to it, thus corrupting memory.

Also it's a good idea to reserve space for trailing \0 by allocating MAXPATH+1 elements, and not MAXPATH. Though might be not needed in this particular place, reserving one more char sometimes saves you hours of memory corruption bug tracing.

Try

wchar_t filename[MAX_PATH]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top