0

I've been following MSDN's example on enumerating registry subkeys.

http://msdn.microsoft.com/en-us/library/windows/desktop/ms724256%28v=vs.85%29.aspx

In the following code, I don't understand why achValue[0] = '\0'; is necessary. I ran some tests querying HKCU and HKCU\Console and the output was as expected. I then ran the same test with the line commented and got the same output. I had thought null-terminating the first TCHAR would prevent the TCHAR array from concatenating each value name (achValue), but this is undoubtedly incorrect.

if (cValues) 
{
    printf( "\nNumber of values: %d\n", cValues);

    for (i=0, retCode=ERROR_SUCCESS; i<cValues; i++) 
    { 
        cchValue = MAX_VALUE_NAME; 
        achValue[0] = '\0'; 
        retCode = RegEnumValue(hKey, i, 
            achValue, 
            &cchValue, 
            NULL, 
            NULL,
            NULL,
            NULL);

        if (retCode == ERROR_SUCCESS ) 
        { 
            _tprintf(TEXT("(%d) %s\n"), i+1, achValue); 
        } 
    }
}

Also, why is the TCHAR array only null-terminated in the cValues if block? The TCHAR array achKey in the cSubKeys if block of the MSDN example does not follow the same procedure.

Thank you.

Hugh McMaster
  • 319
  • 3
  • 10
  • My guess for the null-termination is that it allows you to guarantee that `achValue` is null-terminated in the case where `RegEnumValue` doesn't write data into it (in cases of error, etc). It's only null-terminated in the `if` block, as that's the only place it's used. Why is it different for `achKey`? Don't know, perhaps because it's just an example. Add something to the page if you think it needs it. – icabod Jun 18 '14 at 12:15
  • @icabod the string is only read if the function succeeds – David Heffernan Jun 18 '14 at 12:27

1 Answers1

2

The example is misleading. The function does not require the value upon input to be null-terminated.

You can remove the line of code in question. It obviously does not do any harm to include the line, but it is superfluous.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490