Bruce Eitman

Windows CE Musings

  Home  |   Contact  |   Syndication    |   Login
  101 Posts | 0 Stories | 107 Comments | 0 Trackbacks

News

Tag Cloud


Archives

Post Categories

I made a change to a string value in the registry recently. That seemed like a harmless thing to do, didn’t it? But, what I did was make the string longer than it was before, again seemed harmless.  Harmless until some applications started reading the value into arrays with hard coded length, the problems began.
The problem is that RegQueryValueEx() does not have a parameter to indicate the size of the buffer that it will put data into.  This means that if the data is bigger than the buffer, RegQueryValueEx() will write past the buffer causing problems for your system.  The good news is that you can use RegQueryValueEx() to discover the size of the buffer that is required, and then allocate a buffer that is large enough.
So the following code reads a string from the registry by getting the string length first, then allocating a buffer, then reading the string:
TCHAR *EventName = NULL;
DWORD Result;
HKEY hKey;
DWORD NumBytes = 0;
DWORD Type;
HANDLE UserEvent = INVALID_HANDLE_VALUE;
 
// Open the Registry Key
Result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, (LPCWSTR)GWE_REG_PATH, 0, 0, &hKey);
 
if( ERROR_SUCCESS == Result )
{
                // This is a fake read, all it does is fill in NumBytes with the number of
                // bytes in the string value plus the null character.
                Result = RegQueryValueEx( hKey, ACTIVITY_VALUE, NULL, &Type, NULL, &NumBytes );
                if( NumBytes > 0 )
                {
                                // Now we know how big the string is allocate and read it
                                EventName = (TCHAR *)malloc( NumBytes );
                                if( EventName != NULL )
                                                Result = RegQueryValueEx( hKey, ACTIVITY_VALUE, NULL, &Type,
                                                                (LPBYTE)EventName, &NumBytes );
                }
                RegCloseKey( hKey );
 
                UserEvent = CreateEvent( NULL, FALSE, FALSE, EventName );
                free( EventName );
}
 
// Do something with UserEvent
posted on Wednesday, June 11, 2008 12:48 PM

Feedback

# re: Windows CE: Reading a String from the Registry 6/12/2008 4:01 PM Chris Tacke
The high risk of a leak with this code is, IMO, a bad, bad thing. I'd refactor it to have the buffer passed in as a parameter and the buffer length as well. No point in propagating bad code into the wild.

http://blog.opennetcf.com/ctacke/2006/12/19/ReturningStringsFromCFunctions.aspx


# re: Windows CE: Reading a String from the Registry 6/12/2008 6:21 PM Bruce Eitman
Of course you are right Chris. I updated it to eliminate that.

Post Feedback

Title:
Name:
Email: (never displayed)
Url:
Comments: 
Please add 1 and 6 and type the answer here: