Question about a valid file path
I am using the following code to create a file, but it always failed with error code 123 (the path syntax is not valid).
The strange thing is: path_ok is always ok, but path_err always failed with 123. And after the failure, the buffer that path_err points to is cleared.
Could anyone shed some light on me? I have checked the memory of the 2 pointers, and their contents seems to be identical.
Many thanks.
WCHAR *pDumpFileName = ComposeDumpFileName();
WCHAR *path_ok = _T("d:\\myapp_Utopia_2010-11-15_04-22-05.dmp");
WCHAR *path_err = pDumpFileName;
::wprintf(pDumpFileName);
HANDLE hFile = ::CreateFileW( pDumpFileName, GENERIC_READ | GENERIC_WRITE,
0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
The ComposeDumpFileName() function is like this:
WCHAR* ComposeDumpFileName(void)
{
// get the time
SYSTEMTIME sys_time;
::GetSystemTime(&sys_time);
// get the computer name
WCHAR computer_name[MAX_COMPUTERNAME_LENGTH + 1];
DWORD computer_name_len = ARRAYSIZE(computer_name);
::GetComputerNameW(computer_name, &computer_name_len);
// build the filename: APPNAME_COMPUTERNAME_DATE_TIME.DMP
WCHAR dump_file_path[MAX_PATH];
::swprintf_s(dump_file_path, ARRAYSIZE(dump_file_path),
_T("d:\\myapp_%s_%04u-%02u-%02u_%02u-%02u-%02u.dmp"),
computer_name, sys_time.wYear, sys_time.wMonth, sys_time.wDay,
sys_time.wHour, sys_time.wMinute, sys_time.wSecond);
return dump_file_path;
}
Update
In my above code, when I execute the following code:
WCHAR *pDumpFileName = ComposeDumpFileName();
After the ComposeDumpFileName returned, its stack frame is invalid, however, its local variable WCHAR dump_file_path[MAX_PATH] still exists on the stack. So this explains why I can still see its content though the stack space for it is invalid already.
Then I execute the following statement:
::wprintf(pDumpFileName);
HANDLE hFile = ::CreateFileW( pDumpFileName, GENERIC_READ | GENERIC_WRITE,
0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
The wprintf() and CreateFileW() has their own stack frames. Though in the debugger, I found that wprintf()'s stack frame didn't destroy the memory content pointed by the pDumpFileName, the CreateFileW could have, so it complains a开发者_开发百科bout a invalid path syntax.
This is my current understanding, please correct me if I am wrong.
Thanks.
One major problem with your code is the buffer you are returning is on the stack and this is a big no no:
// build the filename: APPNAME_COMPUTERNAME_DATE_TIME.DMP
WCHAR dump_file_path[MAX_PATH];
Either change it to be a static:
// build the filename: APPNAME_COMPUTERNAME_DATE_TIME.DMP
static WCHAR dump_file_path[MAX_PATH];
or pass the buffer into the function.
精彩评论