Search code examples
c++windowswinapiregistryrights

RegOpenKeyEx and RegSetValueEx fail, but I dont know why


As a starting C++ programmer I want to set a value in the windows registry. I created this textbook implementation to accomplish this, but I always get error 998 back. I guess I am missing something very simple and straightforward, but I can't figure out what it is.

Running this code as a regular user or administrator makes no difference.

#define LEDPORT 3
#define SUBKEY "SOFTWARE\\PATH\\OTHERPATH\\"

    HKEY key;
    if(RegCreateKey(HKEY_LOCAL_MACHINE,  TEXT(SUBKEY), &key) == ERROR_SUCCESS)
    {
        HKEY createKey;
        DWORD value = LEDPORT;

        if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT(SUBKEY), NULL, KEY_ALL_ACCESS, &createKey) == ERROR_SUCCESS){

            // retVal returns error 998 and the value isn't set
            int retVal = RegSetValueEx(createKey, TEXT("PortNumber"), NULL, REG_DWORD, (BYTE *)value, sizeof(value));


            RegCloseKey(createKey);
        }
    }

In effect this creates the mentioned key at LocalMachine\Software\Path\OtherPath but the DWORD value "PortNumber" isnt.

Again, I think it is something straightforward, but I spend a couple of hours of thinking what it could be and I can't figure it out.


Solution

  • Error code 998 converted into human-readable is Invalid access to memory location. The reason is your cast (BYTE*)value, reinterpreting the value 3 (LEDPORT) as an address. (BYTE*)&value fixes your immediate problem.