Jengerer
Jengerer

Reputation: 1163

Strange error trying to read registry value with Windows/C++

I'm trying to read the install path for an application, and I'm baffled at the behaviour I'm getting. First, here's the code that didn't work (formatted it a little so it doesn't take up a huge line):

LONG status = RegQueryValueEx(
    hkRegistry,
    "InstallPath",
    0,
    &regType, (LPBYTE)installPath,
    &regSize );
if (status == ERROR_SUCCESS) {
    // Handle success.
}

I realized that it was failing on the call to RegQueryValueEx, so I decided to probe the return value by throwing it within an exception by adding:

else {
    throw Exception( status );
}

But then... the code started to work and the call to RegQueryValueEx succeeded. I've been able to repeat this behaviour as long as I throw something within the else. If I comment out the body of the else, the error returns.

Edit: Okay, I tried calling MessageBox instead of an exception and I get the same behaviour. If I comment it out, it stops working again.

Is there a rational explanation for this?

Upvotes: 0

Views: 532

Answers (1)

Sven
Sven

Reputation: 22703

It's possible that the buffer for installPath is too small compared to the value contained in regSize (which must be initialized to the size of the buffer).

If installPath is a stack-allocated value I suspect that it is overflown, causing the value of status to get overwritten.

Upvotes: 1

Related Questions