C++ application crash when trying to read registry subkey

0

I'm writing a programme that should return the Value of a registry subkey. I tried this code:

LPCTSTR sk = TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\");
HKEY regkey;
char out[255];
RegOpenKeyEx(HKEY_CURRENT_USER, sk, 0, KEY_SET_VALUE, &regkey);
RegGetValue(regkey, L"test", NULL, RRF_RT_ANY, NULL, (PVOID)&out, (LPDWORD) strlen(out) +1);
RegCloseKey(regkey);
MessageBox(NULL, (LP) out, L"Output", MB_OK);

I wrote this in Visual Studio 2017 and it doesn't show any errors. But when I run it, it crashes on line 5.

Crash reason:

Exception Error on 0x7511C481 (KernelBase.dll) in reader.exe: 0xC0000005: Access Violation While Reading at Location 0x00000005. (Translated by Google Translate)

I have already checked if RegOpenKeyEx() works and yes it does work.

What am I doing wrong and how to fix it?

c++
windows
asked on Stack Overflow Nov 9, 2017 by user5636344 • edited Nov 9, 2017 by user5636344

1 Answer

2

You should use sizeof(out) and not strlen(out)+1. That variable is uninitizlied and depending on how you build this can either be filled with zeros (in which case you're telling RegGetValue() it can write 1 bytes into it) or it can have random data (in which case you're telling RegGetValue() it can write a random number of bytes).

The second issue is that RegOpenKeyEx() is called with KEY_SET_VALUE so you don't even have permission to read. You need KEY_QUERY_VALUE.

The third issue, and the one probably causing the crash, is that you cast the result of strlen(out)+1 to a pointer. It's a number, not a pointer. The function is expecting a pointer so it can write the number of bytes it actually read. Use:

DWORD len = sizeof(out);
RegGetValue(regkey, L"test", NULL, RRF_RT_ANY, NULL, (PVOID)&out, &len);

And finally, as all the comments mention, you should check for errors on all functions and handle all of them.

answered on Stack Overflow Nov 9, 2017 by kichik

User contributions licensed under CC BY-SA 3.0