views:

104

answers:

3
int * ref () {

 int tmp = 100;
 return &tmp;
}

int main () {

 int * a = ref();
 cout << *a << endl;
}

I know the function ref () is allocated stack space. It will get destroyed as soon as the function exits. So the complier will give warning information. But my question is why the returning result is still correct.

+3  A: 

Because the storage space wasn't stomped on just yet. Don't count on that behavior.

msw
+1  A: 

You are just returning a memory address, it's allowed but probably an error.

Yes if you try to dereference that memory address you will have undefined behavior.

int * ref () {

 int tmp = 100;
 return &tmp;
}

int main () {

 int * a = ref();
 //Up until this point there is defined results
 //You can even print the address returned
 // but yes probably a bug

 cout << *a << endl;//Undefined results
}
Brian R. Bondy
I disagree: There is a problem before the `cout`. `*a` points to unallocated (freed) memory. Even if you don't derefence it, it is still dangerous (and likely bogus).
ereOn
@ereOn: I clarified more what I meant by problem, but no it is not dangerous in terms of valid c++ code. But it is dangerous in terms of likely the user made a mistake and will do something bad. Maybe for example you are trying to see how the stack grows, and you only care about the address value and will never dereference it.
Brian R. Bondy
+11  A: 

The result is "correct" because you are getting (un)lucky. Dereferencing a pointer to an object that no longer exists results in undefined behavior.

It just so happens that the location in memory where tmp was stored has not been overwritten. If you were to call another function before dereferencing the pointer, then tmp will likely have been overwritten and the likely result would be that you would see some garbage value printed.

James McNellis