2

I have compiled and run the following C++ code with g++ version 4.8.2:

vector<int> ivec{0,1,2};
int& iref = ivec[1];
for (int i=3;i<100;++i)
   ivec.push_back(i);
iref = 10;
cerr<<"After Error"<<'\n';
return 0;

The program will crash as expected at line iref = 10;, because the reference is invalidated. But the string "After Error" gets printed. Why?

The answer to this question is important to me, because most of the time I use cout or cerr to find the line causing a run-time error.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
  • Did you specify `-O0` on compilation? – timrau Jun 18 '15 at 16:35
  • I've tried that and It does not change anything. – MrDetective Jun 18 '15 at 16:37
  • What seems to be happening is that `iref = 10;` is corrupting the stack, but this does not cause a crash - you don't find out about it until `main()` tries to return. This explains why you see the debug output before the seg fault error message. – Paul R Jun 18 '15 at 16:41
  • @PaulR Thank you for your answer. So, Should I use "cout" instead of "cerr" to track runtime-errors? – MrDetective Jun 18 '15 at 16:48
  • It won't make any difference - it's not uncommon for the effect of a bug to not show up until later (or maybe not even show up at all). This is typical of bugs that corrupt memory in some way - they are called latent bugs. Programmers typically use stress testing tools to flush out such bugs (e.g. valgrind). – Paul R Jun 18 '15 at 16:51
  • 1
    @PaulR Thank you. Your answer was the most helpful. – MrDetective Jun 18 '15 at 17:00

1 Answers1

6

Your program has undefined behaviour because push_back invalidates the reference iref. The C++ standard does not specify any behaviour for the execution of your program. The question "why" cannot be answered in the context of C++.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • So, how should we track runtime-errors caused by undefined behavior? should we use "cout" instead of "cerr"? (when I use "cout" the string does not get printed, which is probably because the output buffer is not flushed). I thought "cerr" was designed to help debugging process. – MrDetective Jun 18 '15 at 16:44
  • http://stackoverflow.com/questions/7237963/a-c-implementation-that-detects-undefined-behavior this might provide some insight – Ediac Jun 18 '15 at 16:44
  • @Ediac Thank you very much. I was looking for a tool to detect undefined behaviors (at least most of them). – MrDetective Jun 18 '15 at 16:54