以下代码是会发生些错误的,在vs2010下回崩溃。
//1. CString strPath = GetCurWorkDir();
//2. AfxMessageBox(strPath);
char* p;// = new char[10];
*p = 'a';但打开注释1后就不会崩溃,能正常运行,调试时发现p指向了strPath得空间,怎么解释?如果这样那就是隐患了。怎么避免?烦请解答,分不多。以下为GetCurWorkDir实现:
CString GetCurWorkDir()
{
CString strPath;
TCHAR szFull[MAX_PATH];
TCHAR szDrive[_MAX_DRIVE];
TCHAR szDir[_MAX_DIR];
GetModuleFileName(NULL, szFull, sizeof(szFull) / sizeof(TCHAR));
_tsplitpath(szFull, szDrive, szDir, NULL, NULL);
_tcscpy(szFull, szDrive);
_tcscat(szFull, szDir);
//strPath = (CString)szFull;
strPath.Format("%s", szFull);
return strPath;
}
//1. CString strPath = GetCurWorkDir();
//2. AfxMessageBox(strPath);
char* p;// = new char[10];
*p = 'a';但打开注释1后就不会崩溃,能正常运行,调试时发现p指向了strPath得空间,怎么解释?如果这样那就是隐患了。怎么避免?烦请解答,分不多。以下为GetCurWorkDir实现:
CString GetCurWorkDir()
{
CString strPath;
TCHAR szFull[MAX_PATH];
TCHAR szDrive[_MAX_DRIVE];
TCHAR szDir[_MAX_DIR];
GetModuleFileName(NULL, szFull, sizeof(szFull) / sizeof(TCHAR));
_tsplitpath(szFull, szDrive, szDir, NULL, NULL);
_tcscpy(szFull, szDrive);
_tcscat(szFull, szDir);
//strPath = (CString)szFull;
strPath.Format("%s", szFull);
return strPath;
}
CString strPath在退出GetCurWorkDir后就应该释放了,那么strPath = GetCurWorkDir是不是就没有得到值呢?
char* p;
编译器 并没有 给 p 一个 确定值。(p 的值是 不确定的)
应该:
char* p=0;
但是GetCurWorkDir中的CString strPath作为一个局部变量,退出函数后应该消失,CString strPath = GetCurWorkDir就会得不到正常的值,但是可以得到,怎么解释?烦请解答。
return strPath;// 这个值被 复制 后 作为 返回值, 然后 这个值 才消失!
返回值 不会 消失 !“p指向strPath空间应该是编译器处理的” 不是的, 是随意的。