Programmatically read a string from the Windows CE registry.
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 NumBytes = 0;
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
Note: This article is written by Bruce Eitman, and is posted to the Embedded101 site with Bruce’s permission.
Copyright © 2010 – Bruce Eitman – All Rights Reserved