jack excell
jack excell

Reputation: 141

Why does my registry reading program fail?

Regedit Screenshot http://i54.tinypic.com/3503vi8.jpg

Now, this code:

HKEY hKey;
LONG regOpenCriss = RegOpenKeyEx(HKEY_CURRENT_USER, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\", 0, KEY_QUERY_VALUE, &hKey);
char mydata[2000] = {'\0'};
DWORD dwType = REG_SZ;
DWORD dataLength = sizeof(mydata);
LPVOID messagecaliss;
GetLastError();
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
    NULL, GetLastError(), NULL,(LPTSTR) &messagecaliss, 0, NULL );

if (regOpenCriss == ERROR_SUCCESS) {
    RegQueryValueEx(hKey, "Test2", 0, &dwType, (LPBYTE)&mydata, &dataLength); //change the key you want to read
    printf("%s\n", mydata);
    system("PAUSE");
    RegCloseKey(hKey);
}
else
    MessageBox(NULL,(LPCTSTR)messagecaliss,"ERROR",MB_OK|MB_ICONINFORMATION);
printf("%s\t\n", mydata);
std::string FullPath(mydata,dataLength-1);
printf("%s\n", FullPath);
std::string FileName = GetFileNameFromPath(mydata);
printf("%s\n", FileName);
system("PAUSE");

The function GetFilenameFromPath is defined as:

std::string GetFileNameFromPath (std::string str) {
size_t found;
found=str.find_last_of("/\\");
return str.substr(found+1);}

When I call RegQueryValueEx with "QKSMTPServer3" as the second parameter, here is the output:

C:\Program Files (x86)\QK SMTP Server 3\QKSmtpServer3.exe
Press any key to continue . . .
C:\Program Files (x86)\QK SMTP Server 3\QKSmtpServer3.exe
C:\Program Files (x86)\QK SMTP Server 3\QKSmtpServer3.exe
QKSmtpServer3.exe
Press any key to continue . . .

Which is what I want. Now, when I call RegQueryValueEx with "Test2", I get:

C:\Test.exe
Press any key to continue . . .
C:\Test.exe

and the program crashes. Any ideas why??

Thank you very much

Upvotes: 1

Views: 255

Answers (1)

Billy ONeal
Billy ONeal

Reputation: 106530

  1. Your code is not exception safe. If std::string's member functions throw std::bad_alloc, you will leak a handle (the HKEY).
  2. Check for error return codes and GetLastError for a more specific reason why your code is failing.
  3. printf("%s\n", FullPath); should not compile, much less run. Are you sure it's not printf("%s\n", FullPath.c_str());?
  4. Rather than a fixed size buffer, you should use std::vector. If you know that you're always going to be getting a file name, you should use MAX_PATH as your buffer size.
  5. This code fails if Unicode characters are involved at all. Consider switching everything over to wchar_t instead.
  6. char mydata[2000] = {'\0'}; <-- Why {'\0'} instead of just "" or {}?
  7. You're not doing anything with the return code of GetLastError();
  8. If there's no \ or / in the string, GetFileNameFromPath will fail because std::string::find will return string.npos.
  9. system("PAUSE"); should really be replaced with std::cin.get(); instead.

Upvotes: 1

Related Questions