user13739935
user13739935

Reputation:

Condition For Invalid Pointer

Invalid pointer is a pointer point to an address can't access by current program, if try to use invalid pointer, then OS will block it happen, in C++ Primer chapter 2 said

Using an invalid pointer as a condition or in a comparison is undefined

but I am just try to compare pointers, not dereference them, how to explain that sentence in C++ Primer?

Upvotes: 0

Views: 181

Answers (1)

Sorin
Sorin

Reputation: 11968

The primer says the behavior is undefined.

In most cases leaving the behavior undefined is done because saying anything else (as in comparing an invalid pointer returns false) would mean some performance cost (extra memory, an extra check). It doesn't mean that the comparison will not return a result. It means that the compiler can do anything it wants at that point (this includes time travel).

Since the compiler is allowed to do anything in this case, it can assume that both pointers are valid and skip checks for validity around them. It can assume that the result is whatever it allows it to remove most of the code (in case you use it in an if).

In addition, since at this point no one can tell you what the result of the comparison is, how can anyone argue that the program is correct (that is it will do what you say it's supposed to do)?

So:

  • Can you compare invalid pointers? Sure.
  • Is the result stable? Probably not.
  • Will this crash? Maybe.
  • Should you use it in a program? No. Avoid at all costs.

Upvotes: 1

Related Questions