A variable of type HANDLE can be compared with NULL in C?

153 Views Asked by At

A variable declared as HANDLE can be compared with NULL in C? Thank you.

Edition:

For example:

HANDLE hProcess = NULL;

status = ZwOpenProcess(&hProcess, PROCESS_DUP_HANDLE, &ob, &Cid);
if (hProcess != NULL)
{
  ZwClose(hProcess);
  hProcess = NULL;
}

The goal is check if hProcess is != 0. Then if i'm checking != NULL, means the same thing?

2

There are 2 best solutions below

0
dxiv On BEST ANSWER

(Too long for a comment.)

The goal is check if hProcess is != 0.

You can check that with if(hProcess != NULL) { /*...*/ } as explained in the other answers.

However, in the given example what must be checked is the return value of the API call, instead.

  HANDLE hProcess;
  if(NT_SUCCESS(ZwOpenProcess(&hProcess, PROCESS_DUP_HANDLE, &ob, &Cid)))
  {
    /*... use hProcess ...*/

    ZwClose(hProcess);
  }
  else
  {
    /*... handle error ...*/
  }
0
Sourav Ghosh On

Any pointer type, can be compared against NULL. The result will be falsy (i.e., it'll be unequal), assuming the oroginal variable holds any value other than a null pointer of that type.

Quoting C11,

[...] If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.