0

I am reading Learning a New Programming Language: C++ for Java Programmers here, and there is an example on pointers that reads:

Never dereference a dangling pointer (a pointer to a location that was pointed to by another pointer that has been deleted):

  int *p, *q;
  p = new int;
  q = p;           // p and q point to the same location
  delete q;        // now p is a dangling pointer
  *p = 3;          // bad!

However, if I copy this code into a main function and add the following cout:

  cout << p << " " << *p << endl;

I get the output:

  0000022DC3DD0EF0 3

Which seems valid to me, I get the pointer and then the deref'd value.

Is this a typo in the webpage, or is the above code bad practice?

David Cruz
  • 113
  • 1
  • 7
  • 1
    Go read about [undefined behavior](https://www.google.com/search?q=undefined+behavior). C++ isn't a friendly language where doing something wrong gives you a nice error message. Errors in C++ are far more subtle in their nastiness. – user2357112 Oct 16 '16 at 20:58
  • The results you got are not guaranteed. After further allocations, it may be overwritten. – Steve Oct 16 '16 at 20:58
  • 1
    p ans q point to the same memory address. After you free the memory at that address with delete no pointer pointing to that address should access it even if you can. The fact that you get a valid output is pure luck. If The memory address is given to another object in the meantime you have less luck. – Jhonny007 Oct 16 '16 at 21:01
  • http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior – Captain Giraffe Oct 16 '16 at 21:02

3 Answers3

0

This is undefined behavior. You cannot access memory through a deleted pointer. That is a coincidence.

Rikocar
  • 79
  • 4
0

When you delete object it's memory is marked as free and can be used by other objects or even returned to OS. But nobody wastes CPU for erasing the object from memory. So p is still there but it is not yours anymore. You can't be sure what is stored in that place or even that you still have right to read the memory.

Your example is very simple so it's behaviour is predictable. When there is much work done between removal of the object and accessing it's memory, things go weird. And what's worse, such bugs are floating, sometimes code works correctly and sometimes not. So they are hard to debug.

Alexey Guseynov
  • 5,116
  • 1
  • 19
  • 29
0

Which seems valid to me, I get the pointer and then the deref'd value.

Among the behaviors allowed by the term "undefined behavior" is to produce results that sucker you into thinking everything is fine. (and then stop working in a more complex program giving you lots of grief because you believe that this can't possibly be the problem)