Sim*_*ons 0 c++ windows cstring
我有以下代码,它从函数中获取返回值 char*
cDestDrive = ReadFromRegistry(HKEY_CURRENT_USER,NDSPATH,szDestPathRoot);
Run Code Online (Sandbox Code Playgroud)
我可以读取内部的值,cDestDrive 直到我分配它为止.我分配它的那一刻:
CString strServerAddress = cDestDrive;
Run Code Online (Sandbox Code Playgroud)
cDestDrive的值被更改(损坏),我无法获得CString strServerAddres任何想法的价值,为什么会发生这种情况.
编辑: 从注册表中读取的代码
char* CNDSShellExtender::ReadFromRegistry(HKEY hKey,LPCTSTR lpNDS,LPSTR lpRegKey)
{
HKEY hRegKey=NULL;
if(hKey==NULL || lpNDS==""||lpNDS==NULL||lpRegKey==""||lpRegKey==NULL)
MessageBox(NULL,"Reading from Registry Failed!Invalid Path",
_T("Network Drive Solution"),
MB_ICONERROR);
LONG lOpenRes=RegOpenKey(hKey,lpNDS,&hRegKey);
if (lOpenRes!=ERROR_SUCCESS ||lpNDS==NULL)
MessageBox ( NULL, "Can not Find Any Server to Connect",
_T("NDSShellExtension"),
MB_ICONERROR );
if(lOpenRes==ERROR_SUCCESS && lpNDS!=NULL)
{
TCHAR tSZValue[MAX_PATH] = {0};
DWORD dwBufSize=MAX_PATH;
LONG lCloseOut;
LPBYTE lpStorage = reinterpret_cast<LPBYTE>(tSZValue);
char* cpRegKeyVal=tSZValue;
if (ERROR_SUCCESS == RegQueryValueEx(hRegKey,lpRegKey , 0, 0, (BYTE*)tSZValue, &dwBufSize))
{
lCloseOut= RegCloseKey(hRegKey);
if (lCloseOut != ERROR_SUCCESS)
MessageBox (NULL, "Registry Not Closed",
_T("NDSShellExtension"),
MB_ICONERROR );
return cpRegKeyVal;
}
else
{
lCloseOut= RegCloseKey(hRegKey);
if (lCloseOut != ERROR_SUCCESS)
MessageBox (NULL, "Registry Not Closed",
_T("NDSShellExtension"),
MB_ICONERROR );
return "";
}
}
return "";
}
Run Code Online (Sandbox Code Playgroud)
我相信你正在返回一个char*指向一个在堆栈上分配的数组,即这一行:
TCHAR tSZValue[MAX_PATH] = {0};
Run Code Online (Sandbox Code Playgroud)
其次是:
char* cpRegKeyVal=tSZValue;
Run Code Online (Sandbox Code Playgroud)
这很危险,您正在亲身体验最终结果!
编辑:为什么不直接分配给函数中的CString并返回?
| 归档时间: |
|
| 查看次数: |
371 次 |
| 最近记录: |