1

I am new to C++ and ran into following supposedly bug, but somehow my program just works.. Here is the code

#include<iostream>
#include<queue>
#include <string>


int main()
{
 string s ("cat");
 queue<string> _queue;
 _queue.push(s);
 string & s1 = _queue.front();
 _queue.pop();
 // at this time s1 should become invalid as pop called destructor on s
 std::cout << s1 << std::endl;
 return 0;

 }

It just works, even though s1 is a reference to an invalid object. Is there a way i can assert that s1 truely refers to an invalid object?

Jimm
  • 8,165
  • 16
  • 69
  • 118
  • 2
    This is textbook [undefined behavior](http://en.wikipedia.org/wiki/Undefined_behavior), which by definition is not "detectable" at runtime, because you're already in UB-land. – ildjarn Oct 05 '12 at 22:12
  • Ty for the excellent link to UB. – Jimm Oct 05 '12 at 22:20
  • See [Can a local variable's memory be accessed outside of its scope?](http://stackoverflow.com/a/6445794/597607) – Bo Persson Oct 06 '12 at 10:46

1 Answers1

5

Trying to access a destroyed object the way you do it in your code results in undefined behavior. And no, there's no language-provided way to perform a run-time check for this situation. It is entirely your responsibility to make sure things like that do not happen in your code.

The fact that "it just works" in your experiment is just an accident (with certain degree of typical computer determinism, as usual). Something completely unrelated might change in your program, and this code will no longer "work".

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • Slightly related, would it be UB even if the memory was never accessed, ie you made a custom allocator which had a method to assert a pointer for validity? Not useful normally, but could be for a test. – Joachim Isaksson Oct 05 '12 at 22:16
  • wonder why c++ runtime does not zero out the released memory ? – Jimm Oct 05 '12 at 22:24
  • @Jimm : Some implementations do, it's dependent on the allocator. But, why should it need to? What benefit does that give? Any code that would rely on that has a bug. – ildjarn Oct 05 '12 at 23:16
  • @Jimm: Firstly, some implementations do in "debug" configurations, to help you catch bugs in your code, i.e. to make it crash more reliably in response to invalid memory access. They don't zero it though, but rather fill it with some sort of "bad" pattern. Secondly, in this particular example the memory is not necessarily released. The object is destructed, but the raw memory is likely retained by the queue object. So, pedantically speaking, it is not about released memory, but rather about memory occupied by now-destructed objects. – AnT stands with Russia Oct 06 '12 at 01:35