Since there was positive feedback on the last one - here is another.  I will post hints and the solution next week.  There are multiple defects in this code.

I added the _tmain to give some context on how the function getVersionString might be called.  The defects I'm interested in are in the function getVersionString.

The function's requirements are to populated the user provided buffer with the version string from the registry and to return a HRESULT indicating success or failure.  Also the size of the string should be returned as well.

Found the defects?  Want to ask a question or discuss an issue?  Post your comments by clicking on the Feedback link on the bottom of the post.  Don't want to post in public?  Email me instead.


#include <tchar.h>

#include <windows.h>

 

inline HRESULT HRESULT_FROM_GetLastError()

{

      DWORD dw = GetLastError();

      return HRESULT_FROM_WIN32(dw);

}

 

HRESULT getVersionString(LPTSTR lpszValue, size_t cchLengthIn, size_t *cchLengthOut)

{

      HRESULT hr = E_FAIL;

      LONG cbLength = (LONG)cchLengthIn * sizeof(TCHAR);

     

      const TCHAR lpszVersionKey[] = _T("Software\\MagicApp");

 

      if(ERROR_SUCCESS == RegQueryValue(HKEY_CURRENT_USER, lpszVersionKey, lpszValue, &cbLength))

      {

            *cchLengthOut = cbLength / sizeof(TCHAR);

            hr = S_OK;

      }

      else

      {

            // e.g. ERROR_MORE_DATA

            hr = HRESULT_FROM_GetLastError();

      }

 

      return hr;

}

 

int _tmain()

{

      TCHAR lpszVersion[256];

      size_t cchOut = 0;

 

      HRESULT hr = getVersionString(lpszVersion, sizeof(lpszVersion)/sizeof(lpszVersion[0]), &cchOut);

 

      return SUCCEEDED(hr) ? EXIT_SUCCESS : EXIT_FAILURE;

}