RegCreateKeyEx returns ERROR_BADKEY  
Author Message
Harmomelodic





PostPosted: Visual C++ General, RegCreateKeyEx returns ERROR_BADKEY Top

I realize this is probably a dumb formatting problem, but I'm banging my head against a wall trying to figure it out.

Here is a code snippit.

_tcscpy(szBuffer, TEXT("Software\\TSDPP"));

errorcode = RegCreateKeyEx(HKEY_CURRENT_USER, szBuffer, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, appsettingkey, &keydisp);

I am getting an errorcode of 1010 (ERROR_BADKEY) and I cannot figure out why.

Thanks in advance.




Visual C++11  
 
 
Mike Danes





PostPosted: Visual C++ General, RegCreateKeyEx returns ERROR_BADKEY Top

Tried it and works fine for me. How is appsettingkey defined. In most cases it's done this way:

HKEY appsettingkey;

errorcode = RegCreateKeyEx(HKEY_CURRENT_USER, szBuffer, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &appsettingkey, &keydisp);

I see that you don't have a & in front of appsettingkey so is it already a pointer initialized to what


 
 
Harmomelodic





PostPosted: Visual C++ General, RegCreateKeyEx returns ERROR_BADKEY Top

Yes, it is already a pointer

PHKEY appsettingkey;

However, I tried changing as you suggested, and it worked!

Weird isn't it. The function must be incapable of allocating the memory for an HKEY on its own. You would think it would be able to deal with this since the function takes a pointer as an argument! It would probably also work ok if I changed it to...

PHKEY appsettingkey = new HKEY;

and deleted it later.

Thank you. I was fixated on my string formatting instead of taking the error 'BADKEY' more literaly.



 
 
Mike Danes





PostPosted: Visual C++ General, RegCreateKeyEx returns ERROR_BADKEY Top

"PHKEY appsettingkey;"

OK, it is a pointer but you did not initialize it to anything, not even NULL.

And yes, the function cannot allocate memory for HKEY on its own. In fact it can allocate memory but it cannot return the pointer to the allocate memory. In order to be able to do that the parameter must be a pointer to another pointer. This complicates things and it's really not needed in this case.

"PHKEY appsettingkey = new HKEY;"

Yes, this works but in most cases it is not necessary. Why bother allocating memory and free it when you can simply declare a variable and pass the address of that variable to the function