There's more to calling a function than just getting the types to match

Raymond Chen

Raymond

Here’s a classic novice error.
You want to call a function, say

GetBinaryType
.

void sample()
{
 if (GetBinaryType(TEXT("explorer.exe"), ????)) {
  ...
 }
}

What should you write for those question marks?
Well, the prototype says that the second parameter is an LPDWORD,
so let’s pass it one.

void sample()
{
 if (GetBinaryType(TEXT("explorer.exe"), (LPDWORD)NULL)) {
  ...
 }
}

Hm, but that crashes. Well, maybe we can pass it an LPDWORD this way:

void sample()
{
 LPDWORD lpdw;
 if (GetBinaryType(TEXT("explorer.exe"), lpdw)) {
  ...
 }
}

Hm, that still crashes. Oh wait, it’s because of the uninitialized
variable.

void sample()
{
 LPDWORD lpdw = NULL;
 if (GetBinaryType(TEXT("explorer.exe"), lpdw)) {
  ...
 }
}

No, that still crashes.
Hang on, I know where I can get an LPDWORD.

void sample()
{
 LPDWORD lpdw = new DWORD;
 if (GetBinaryType(TEXT("explorer.exe"), lpdw)) {
  ...
 }
}

This code finally works!
Okay, on to the next problem…

Of course, the seasoned programmer still shakes his head.
Just because the function prototype says that the parameter is an
LPDWORD doesn’t mean you have to have a variable whose type is LPDWORD.
You merely need an expression whose type is
LPDWORD.

void sample()
{
 DWORD dw;
 if (GetBinaryType(TEXT("explorer.exe"), &dw)) {
  ...
 }
}

Why am I telling you this?

No, I’m not trying to insult your intelligence.
I’m trying to get you to think like a novice.
Sometimes you’ll be reading a chunk of code and
find something bizarro, like the fragments above
with the new DWORD.
When you do (for example, when chasing the memory leak
in that code sequence),
don’t tear your hair out trying to find
some deep meaning for the seemingly roundabout way
of accomplishing a simple task.
If you can think like a novice, you will
merely recognize it as a classic beginner mistake,
fix it, and get on with your life.

[While Raymond was on vacation,

the autopilot stopped working

due to

a power outage
.
This entry has been backdated.]

Raymond Chen
Raymond Chen

Follow Raymond