RaHuL
RaHuL

Reputation: 103

Why is an exception thrown (read access violation) when I cout a NULL pointer?

As NULL pointer assigns zero to its value.

  1. When I try to cout a null pointer it throws an exception, why is that? It is not outputting zero.

  2. does the value zero have any address?

Example code :

int main()
{
    int *q = NULL;
    cout << *q;
    return 0;
}

Upvotes: 0

Views: 1326

Answers (1)

Nikhil Badyal
Nikhil Badyal

Reputation: 1697

The value (i.e., the address) stored in a pointer can be in one of four states:

  1. It can point to an object.
  2. It can point to the location just immediately past the end of an object.
  3. It can be a null pointer, indicating that it is not bound to any object.
  4. It can be invalid; values other than the preceding three are invalid.

It is an error to copy or otherwise try to access the value of an invalid pointer. As when we use an uninitialized variable, this error is one that the compiler is unlikely to detect. The result of accessing an invalid pointer is undefined. Therefore, we must always know whether a given pointer is valid.

Although pointers in cases 2 and 3 are valid, there are limits on what we can do with such pointers. Because these pointers do not point to any object, we may not use them to access the (supposed) object to which the pointer points. If we do attempt to access an object through such pointers, the behavior is undefined.

Upvotes: 1

Related Questions