27

In this paragraph of C++ FAQ usage of delete this construct is discussed. 4 restrictions are listed.

Restrictions 1 to 3 look quite reasonable. But why is restriction 4 there that I "must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it"?

I mean this is yet another pointer. Why can't I reinterpret_cast it to an int or call printf() to output its value?

5
  • related: stackoverflow.com/questions/1861912/…
    – jldupont
    Dec 8, 2009 at 11:50
  • Yes, surely related, but this question is specifically about using "this" value, not any other aspects.
    – sharptooth
    Dec 8, 2009 at 11:52
  • 6
    in fact he said related, not duplicated ;) Dec 8, 2009 at 11:53
  • It is a bit exagerated, maybe "must not" could be replaced with "should not". The pointer is still readable and hasn't changed, but delete makes the pointer value useless unless you use it as a debugging aid.
    – stefaanv
    Dec 8, 2009 at 12:02
  • It is one of many others FAQs. It's just not correct. Dec 8, 2009 at 12:05

7 Answers 7

37

The value of 'this' after calling delete is undefined, and the behaviour of anything you do with it is also undefined. While I would expect most compilers to do something sensible, there's nothing (in the spec) stopping the compiler from deciding that its behaviour in this particular case will be emit code to format your hard-disk. Invoking undefined behaviour is (almost) always a mistake, even when your particular compiler behaves in the way you'd like it to.

You could work around this by taking a copy of the pointer (as an integer) before calling delete.

8
  • 4
    Additionally, the way the compiler behaves today might not be the same as the next version does. Undefined really means "not guaranteed, ever". Dec 8, 2009 at 12:28
  • +1, definitely the correct answer. To extend Lasse's response... "undefined" also implies likely to be inconsistent.
    – D.Shawley
    Dec 8, 2009 at 13:00
  • 3
    Although you could take the integer value of the pointer before deleting it - its a good rule of thumb that if you're circumventing the language's mechanics to tread into "undefined behavior" territory - that you're just asking for trouble, and a better fundamental design to your code should be considered.
    – Mordachai
    Dec 8, 2009 at 14:00
  • 1
    Emitting opcodes for formatting the hard drive? And don't type Google into Google, not even for fun, it could break the internet. Dec 8, 2009 at 21:59
  • 1
    -1 because this reasoning is wrong. For example, void *p = this; delete this; p == p; is also wrong, but it's not because the value of p changed (it didn't).
    – user541686
    Jul 13, 2013 at 7:51
30

The reason that you cannot do anything with a pointer after you delete it (this, or any other pointer), is that the hardware could (and some older machines did) trap trying to load an invalid memory address into a register. Even though it may be fine on all modern hardware, the standard says that the only thing that you can do to a invalid pointer (uninitialized or deleted), is to assign to it (either NULL, or from another valid pointer).

6
  • but wouldn't that be applicable for all pointers? why only for this?
    – Naveen
    Dec 8, 2009 at 12:11
  • 3
    I'll accept this answer because it explains why exactly hell can break loose, not just cites The Standard.
    – sharptooth
    Dec 14, 2009 at 15:06
  • and that "old" hardware is the old Intel x86 family. ;)
    – curiousguy
    Sep 29, 2011 at 2:32
  • While this explains why handling an uninitialised pointer invokes undefined behaviour, I find it highly unplausible for a pointer value (=address) that was perfectly valid before calling delete, that the same value starts triggering hardware traps or similar due to the simple fact that the memory location it points to was deallocated. Indeed the pointer value may already be sitting in such a register at the time delete is called. Jul 13, 2014 at 7:56
  • 2
    @MarcvanLeeuwen: It would be possible (and actually not unreasonable) for a compiler on a platform like the 80286 to have objects larger than 32K be represented as a linked-list of segments, each of which had 32K or less of data and included links to the first, next, previous segment of that object, and an indication of its offset into the object. Each pointer would identify a segment and an offset within it; comparing two pointers would require using the data stored at the base of each pointer's segment to find the start of the object.
    – supercat
    May 29, 2015 at 17:46
29

Aha!

3.7.3.2/4: "... the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage. The effect of using an invalid pointer value (including passing it to a deallocation function) is undefined".

Note that this says "using the value", not "dereferencing the pointer".

That paragraph is not specific to this, it applies to anything that has been deleted.

13
  • +1: even more direct than axa's answer. Very nice find Steve.
    – D.Shawley
    Dec 8, 2009 at 13:01
  • 2
    @naveen, no. p = NULL is still valid. We are changing the pointer to a new location, not using the value of the delete pointer. If it were otherwise, all pointer variables would only be able to be used once.
    – deft_code
    Dec 8, 2009 at 15:30
  • 3
    Agree. p = NULL is fine, but p = p - p; is not Dec 8, 2009 at 16:17
  • 3
    p = p - p; is never valid :)
    – avakar
    Dec 8, 2009 at 17:38
  • 2
    p-p is "zero the integer" not "zero the null pointer constant". The former won't convert to a null pointer whereas the latter will.
    – avakar
    Dec 8, 2009 at 23:24
3

because any action you can take with that pointer could trigger logic which is interpreted on the class methods of that object, which could lead to a crash.

Now, some of the actions you point at could be apparently "safe", but it's difficult to say what happens within any method you can call.

From the post: "must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it"?

All these actions can trigger operator related functions, which are evaluated with an undefined pointer. Idem for casting.

Now if you perform a reintepret_cast, that's probably a different story, and you could probably get along with it, as reinterpret is just a bit by bit reinterpretation, without involving (as far as I know) any method call.

5
  • Why could this prevent me from printing "this" value out?
    – sharptooth
    Dec 8, 2009 at 11:53
  • nothing, you can print the crude value if you want I guess, but you have to be very, very careful. Dec 8, 2009 at 11:58
  • What is an "operator related function"?
    – Roger Pate
    Dec 8, 2009 at 12:23
  • I mean any function calling TheClass::operatorsomething() Dec 8, 2009 at 12:59
  • "Now if you perform a reintepret_cast, that's probably a different story" No, there is no difference. "reinterpret is just a bit by bit reinterpretation" Wrong, reintepret_cast<T*>(x) needs the value of x, and does not "reintepret" the "bits" of x.
    – curiousguy
    Sep 30, 2011 at 0:57
2

For the same reason you would not delete any other pointer and then try and perform any operations on it.

3
  • 1
    I would definitely be able to printf() a pointer value after that. But the FAQ says it shouldn'be done on "this".
    – sharptooth
    Dec 8, 2009 at 11:55
  • 1
    Fair enough, if you really want to :) I suppose the FAQ is just being over-cautious.
    – DanDan
    Dec 8, 2009 at 11:58
  • 3
    sharptooth, printing the value of a freed pointer triggers undefined behavior, just like printing freed this.
    – avakar
    Dec 8, 2009 at 12:29
1

b/c the address that this refers to now, it undefined, and you don't know what might be there...

2
  • 1
    Why could this prevent me from printing "this" value out?
    – sharptooth
    Dec 8, 2009 at 11:54
  • You can print the value of this, but it means nothing.
    – Dani
    Dec 8, 2009 at 12:10
1

In a multi-threaded program, the moment you delete a pointer, the free space can be allocated by another thread, overwriting the space used by this. Even in a single-thread program, unless you're very careful about what you call before returning, anything you do after delete this could allocate memory and overwrite what used to be pointed to by this.

In a Microsoft Visual C++ executable compiled in Debug mode, deleteing a pointer causes its memory to be immediately overwritten with a 0xCC test pattern (uninitialized variables are also initialized with this pattern), to help in identifying dangling pointer bugs such as this one.

This reminds me of when I fixed a bug in a online-playable game in which a Fire object's constructor deleted the oldest Fire if the total number of Fires had reached a certain number. The deleted Fire was sometimes the parent Fire creating a new Fire — bam, dangling pointer bug! It was only due to luck that this bug interacted with the memory allocation algorithm in a completely predictable way (the deleted Fire was always overwritten with a new Fire in the same way) — otherwise it would have caused a desynchronization between online players. I found this bug when rewriting the way the game did memory allocation. Due to its predictability, when I fixed it, I was also able to implement emulation of its behavior for compatibility with older game clients.

1
  • 2
    The question isn't about the accessing memory the pointer points to, but rather accessing the pointer itself (e.g. why even just doing a printf("%p\n", this) would be undefined behavior after a doing a 'delete this') Jun 12, 2014 at 5:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.