1

I have a pointer that sometime ago pointed to alive object, but now this object is dead. Is it true, that if I don't use this dead object (don't dereference pointer, don't use methods, etc) there is no undefined behavior?

Code example:

int* x = new int;
int* y = x;
delete x;
// From now on never use *y, or y->... or something else
// that will "dereference" y.
rubenvb
  • 74,642
  • 33
  • 187
  • 332
Gerald Agapov
  • 210
  • 1
  • 10
  • Yes, but you should be very careful not to use it or not to delete it again. –  Oct 08 '15 at 12:32
  • After the initialization of `y` with `int* y = x;`, x and y are totally interchangeable here; that you freed the memory `x` points to through `x` and not through `y` is irrelevant. You could have said as well `delete y`. Dereferencing either one is equally bad. – Peter - Reinstate Monica Oct 08 '15 at 12:34
  • Yes, I know. This is just an example. My particular use case is much more reasonable. – Gerald Agapov Oct 09 '15 at 13:34

3 Answers3

4

Yes, there is NO undefined behavior in your code. What you get are two dangling pointers, i.e. x and y. They are perfectly fine if you don't dereference them (or free them again), but they represent a major source of errors in C-style code.

Paolo M
  • 12,403
  • 6
  • 52
  • 73
2

It's absolutely fine. A simpler, and more familiar, case is

int* x = new int;
delete x;

The behaviour on dereferencing x is undefined and some programmers will write delete x; x = nullptr; to emphasise this.

Acknowledge @BoPersson, reading x following the delete is, at best, implementation defined, and could include a hardware trap for an invalid address. See Is it legal to compare dangling pointers?

Community
  • 1
  • 1
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • As it turns out here [Is it legal to compare dangling pointers?](http://stackoverflow.com/questions/30694069/is-it-legal-to-compare-dangling-pointers) reading the value of a dangling pointer is at best implementation-defined (C++14) and could include a hardware trap for an invalid address. – Bo Persson Oct 08 '15 at 13:29
1

If you want to prevent this case happen, you can use

std::shared_ptr
std::weak_ptr

But if you want to create this scenario in your program, can you tell why? normally we assume the program is always in good state

  • My use case is very specific. Long story short: I use complicated framework. I don't manage lifetime of my classes, framework does it for me. There are two objects (as members) in my class: one has some data, the another points to the data in the first one. I was wondering if I can declare them in any order or not (because they will be deleted in the reverse order comparing to their declaration). – Gerald Agapov Oct 09 '15 at 13:39