views:

37

answers:

4

So I've been trying to get a REG_SZ value out of the registry and store it as a char*. After looking around the internet this is what I came up with. The problem is that the value I get is not what is stored in the registry, I get a bunch of random garbage. How would I correctly get the value?

HKEY hKey;
char value[256];
// Open the key
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\\", 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
{
    return "";
}

// Read the value
DWORD dwType = REG_SZ;
DWORD dwCount = sizeof(value);
if(RegQueryValueEx(hKey, "ProcessorNameString", NULL, &dwType, (LPBYTE)&value, &dwCount) != ERROR_SUCCESS)
{
    RegCloseKey(hKey);
    return "";
}
// Cleanup and return
RegCloseKey(hKey);
return value;

Also anther quick question. I remember that if my program inst running as admin of Vista/7 then it cant edit the HKLM but can it still read it?

+5  A: 

(Updated, since previous answer was wrong.)

The problem may be that you're returing value, which is a stack-allocated buffer. This will work only if you declared your function as returning a char[256]--if you're trying to return a char*, then the caller is getting the address of the first byte in value, which is now pointing to invalid stack data. You should allocate value as a char* on the heap, which will allow you to return the pointer with impunity.

Whether or not you are allowed to read or edit the registry key depends on what ACLs are applied to the key you're reading. It is possible to set the permissions on the key in such a way that an unelevated user can't even read the key, but it's also possible to set the permissions such that all users can both read and write. The key that you're reading above should be readable by all users, but it won't be modifiable except by admins.

JSBangs
I got the same result.
Lienau
A: 

If your application has no manifest it may or may not read the real HKLM. If it ever tries to write to HKLM registry virtualization will kick in and divert writes and also reads to a virtualized per-user store. You are allowed to read HKLM when you're not an admin, so be sure to add a manifest with asInvoker to prevent virtualization.

Kate Gregory
A: 

The main question is already answered but relating to your access problem. You will have to add a manifest file to elevate your process to administrator if you want write access to the registry.

Brian R. Bondy
A: 
  1. You should not return a non static locally declared variable; try to declare the variable as static char value[256];, it is still a bad practice, but could fix your problem;

  2. If you still get garbage, maybe you're compiling with UNICODE defined. If so, you are calling RegQueryValueExW and you're getting a wide char string (no compile time error as the parameter is casted to (LPBYTE)). Try to disable UNICODE or define your string as a TCHAR.

Lorenzo