-3

I am new to C++ and am following the book "Programming Principles and Practices using C++". I came across something that I could not understand completely. Hopefully someone can help me understand this.

Why is this invalid?

int* p = nullptr;
*p = 7;
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Koel
  • 1
  • 2
  • 1
    Where have you allocated space for `p`? – Stephen Newell Jul 14 '22 at 23:58
  • 2
    @StephenNewell `int *p = nullptr;` allocates space for `p`. Either in automatic or static storage depending where this line was found . – M.M Jul 15 '22 at 00:01
  • You're not reassigning `p`. You're reassigning what `p` points at. And since `p` is a null pointer, reassigning what it points at gives undefined behaviour. – Peter Jul 15 '22 at 00:33
  • I suspect the confusion is that you think you are _reassigning a pointer_. `*p` means "the int that `p` is pointing to". Your code is assigning `7` to the int that `p` is pointing to. It's invalid because `p` is not pointing to an int. – Drew Dormann Jul 15 '22 at 00:33

1 Answers1

6

nullptr is a special address. In particular, nothing can ever be stored there. Attempting to dereference a null pointer is undefined behavior (in fact, it's the first example on that list).

Now, to be clear, what you're doing is not reassigning a pointer itself. Given this code:

int* p = nullptr;
*p = 7;

This is dereferencing the pointer and then reassigning the value of the thing that the pointer is pointing at. And since nullptr does not point at anything, dereferencing a nullptr is undefined behavior, so the assignment is invalid.

Now, given this code:

int q = 42;
int* p = nullptr;
p = &q;

This is reassigning the pointer itself. This is perfectly valid. We started with a pointer that is pointing to nothing, and then tell it to point to something else (in this case, a local variable). Notice that I don't put a * when I assign to p in this example. I never dereference a nullptr, so I never hit that particular problem.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • 2
    Nor is it an address -- it's a keyword, that when assigned to a pointer, causes that pointer to be null – M.M Jul 15 '22 at 00:10
  • It's actually a keyword, but using that keyword gives a null pointer constant, which is a value that compares equal to zero. Before `nullptr` was a language keyword, the equivalent could be achieved by `int *p = 0` (which involved a conversion of an integral value to a pointer type) or (more explicitly) `int *p = (int *)0`. Assigning a pointer to be equal to a null pointer constant (however it is done) gives a null pointer. And dereferencing a null pointer gives undefined behaviour. – Peter Jul 15 '22 at 00:42