0

is the below code wrong ? I am returning reference to local variable ...it should core dump , but it is executing fine . Is the below code is working fine on my system because I am LUCKY ??

#include<iostream>
using namespace std;

class a{
    public:
    int i;
    int arr[20];
    a()
    {
        cout<<"\ninside constructor";
        i=10;
    }
    public:
    static a& ret()
    {
        a chk;
        return chk;
    }
    void say()
    {
        i=10;
        arr[0]=1;
        cout<<"\nHello World\n";
    }

};


int main()
{
(a::ret()).say();
return 1;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
user1057741
  • 265
  • 1
  • 2
  • 10
  • It *shouldn't* do anything. Undefined behavior as it's name implies is... well... undefined. Anything can happen, it's a surprise! – Borgleader Jul 04 '13 at 18:01
  • ["Somebody told me that in basketball you can't hold the ball and run. I got a basketball and tried it and it worked just fine. He obviously didn't understand basketball."](http://c-faq.com/ansi/experiment.html) – Jonathan Wakely Jul 04 '13 at 18:24

2 Answers2

8

it should core dump - nope. It's undefined behavior, anything can happen, including appear to work (which sucks, because it can hide bugs).

Is the below code is working fine on my system because i am LUCKY ??

No, because you're unlucky.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
5

i am returning reference to local variable ...it should core dump

Wrong. it is undefined. it can do whatever it likes to. The object was on the stack, it is still accessible, so you can work with it.

Yes, you are lucky. If it was in real code, it wouldn't be considered as a good luck; "This code contains a serious bug, but it happens to be working fine. Am I lucky"? answer it yourself.

Elazar
  • 20,415
  • 4
  • 46
  • 67