Bill Walton
Bill Walton

Reputation: 823

Deleting registry keys - error in MSDN sample

This MSDN article is supposed to demonstrate how to delete a registry key which has subkeys, but the code is flawed.

The line that says

StringCchCopy (lpEnd, MAX_PATH*2, szName);

causes an exception, which is due to trying to copy to beyond the buffer of lpEnd. I tried correcting the solution by replacing that line with the following

size_t subKeyLen = lstrlen(lpSubKey);
size_t bufLen = subKeyLen + lstrlen(szName)+1;
LPTSTR buf = new WCHAR[bufLen];
StringCchCopy(buf,bufLen,lpSubKey);
StringCchCopy(buf+subKeyLen,lstrlen(szName)+1,szName);
buf[bufLen-1]='\0';

I'm unable to step through the code as the target platform and dev platform are different, but from the logging I've put in the code it looks like it just freezes up, but doesn't throw an exception.

It's frustrating that MSDN articles are wrong...you'd think they would be checked.

Any ideas on how to correct this?

Thanks.

Upvotes: 3

Views: 610

Answers (2)

Mike Kwan
Mike Kwan

Reputation: 24447

If you don't mind having Shlwapi.dll as an additional dependency, it may be easier for you just to use SHDeleteKey. If you're only targetting Vista+, RegDeleteTree (which lives in Advapi32.dll) is another alternative.

Upvotes: 1

Mark Wilkins
Mark Wilkins

Reputation: 41232

That change by itself would not be sufficient. The line of code following it:

        if (!RegDelnodeRecurse(hKeyRoot, lpSubKey)) {
            break;

would also need to change. lpSubKey would need to be replaced with buf since that now contains the full key.

And it probably goes without saying, but be sure to free (delete) buf as part of the cleanup.

However, for correctness, it seems as if it would be better just to fix the original line of code by changing it to pass the correct length (which should be okay since I believe the maximum key length in the registry is 255):

StringCchCopy (lpEnd, MAX_PATH*2 - lstrlen(lpSubKey), szName);

Upvotes: 1

Related Questions