C - RegQueryValueEx sometimes in Release build

c, debugging, registry, release, winapi

Solution

By the definition of RegQueryValueEx, lpcbData is both an In and Out parameter. That is, RegQueryValueEx both reads it and writes to it. It complains because you are passing it without initializing it first with the size of the buffer, which in your case is 1024 (also I recommend that you change TCHAR to BYTE as required by the API; You can convert it to a Unicode string later on).

Try setting it to 1024 before calling the function. If then it fails with ERROR_MORE_DATA, then your buffer is not big enough - in other words, the registry key string is too long - you can either define it to contain more characters, or, better yet, call the function first with a NULL parameter instead of the buffer, and you will get back in lpcbData the required size of the buffer. You can then allocate the required buffer on the heap. Hope this helps!

Problem

This is driving me crazy. I'm compiling my project on Visual Studio 2012. I want to read a `REG_BINARY` registry entry using `RegOpenKeyEx` and `RegQueryValueEx` calls. In Debug (Multi-Threaded Debug) mode, everything works perfectly. However, in Release (Multi-Threaded) mode, `RegQueryValueEx` will VERY often fail with error code `ERROR_MORE_DATA`. Here is the code I am using: ``` HKEY keyHandle; TCHAR lpData[1024]; DWORD lpcbData; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_QUERY_VALUE | KEY_WOW64_64KEY, &keyHandle) != ERROR_SUCCESS){ MessageBox(NULL, L"fail", L"title", MB_OK); return NULL; } else if (RegQueryValueEx(keyHandle, L"DigitalProductId", NULL, NULL, (LPBYTE)lpData, &lpcbData) != ERROR_SUCCESS){ MessageBox(NULL, L"fail!", L"title", MB_OK); return NULL; } MessageBox(NULL, L"success", L"title", MB_OK); ```

Original source