1

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?

  • What is the type of `HANDLE`? – Sourav Ghosh Oct 29 '20 at 06:29
  • @SouravGhosh, `typedef void *HANDLE;` –  Oct 29 '20 at 06:30
  • 1
    @Coringa `can be compared` It can, in the sense that it will compile. Whether you *should* compare it to NULL, or to `INVALID_HANDLE_VALUE`, or to something else entirely, depends on the context however. APIs which return HANDLEs will document what the invalid values are. – dxiv Oct 29 '20 at 06:33
  • 1
    @Coringa The thing to check after that call is `status == STATUS_SUCCESS`. – dxiv Oct 29 '20 at 06:38
  • @dxiv, yes i'm checking `status`. –  Oct 29 '20 at 06:40
  • @Coringa errr.. that's not a _check_. – Sourav Ghosh Oct 29 '20 at 06:41
  • 1
    That function does never return NULL so why would you check against it? "Can we do really strange things?" Yes... "Does it make sense to do really strange things?" No... This is like asking "The postal office either sends me a note that my ordered packet has arrived or a note that it couldn't be delivered. Can I check the newspaper to see if my packet has arrived?" Nothing prevents you from _checking_ but you won't find any sensible information there. – Lundin Oct 29 '20 at 07:58
  • Read [this](https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-ntopenprocess) closely, especially the section about the return value. – Jabberwocky Oct 29 '20 at 08:42
  • @Coringa _"yes i'm checking `status`"_. No, you are not, at least not in the code you posted – Jabberwocky Oct 29 '20 at 08:43
  • I think you can assume that if the return value is `STATUS_SUCCESS` then the `hProcess` value will be valid. – Ian Abbott Oct 29 '20 at 10:04

2 Answers2

3

(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 ...*/
  }
dxiv
  • 16,984
  • 2
  • 27
  • 49
1

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261