RegQueryValueEx not working with a Release version but working fine with Debug
I'm trying to read some ODBC details from a registry and for that I use RegQueryValueEx. The problem is when I compile the release version it simply cannot read any registry values.
The code is:
CString odbcFuns::getOpenedKeyRegValue(HKEY hKey, CString valName)
{
CString retStr;
char *strTmp = (char*)malloc(MAX_DSN_STR_LENGTH * sizeof(char));
memset(strTmp, 0, MAX_DSN_STR_LENGTH);
DWORD cbData;
long rret = RegQueryValueEx(hKey, valName, NULL, NULL, (LPBYTE)strTmp, &cbData);
if (rret != ERROR_SUCCESS)
{
free(strTmp);
return CString("?");
}
strTmp[cbData] = '\0';
retStr.Format(_T("%s"), strTmp);
free(strTmp);
return retStr;
}
I've found a workaround for this - I disabled Optimization (/Od), but it seems strange th开发者_JAVA百科at I needed to do that. Is there some other way? I use Visual Studio 2005. Maybe it's a bug in VS?
Almost forgot - the error code is 2 (as the key wouldn't be found).
You need to initialize cbData
- set it to be MAX_DSN_STR_LENGTH - 1
before calling RegQueryValueEx()
.
The problem is likely configuration-dependent because the variable is initialized by the compiler in one configuration and left uninitialized in another.
Also you'll be much better of using std::vector
for the buffer - less code, better exception safety, less error-prone.
精彩评论