I don't understand how this example can possibly work:
double * GetSalary() {
double salary = 26.48;
return &salary;
}
main() {
cout << *GetSalary(); //prints 26.48
}
salary
is a local variable in GetSalary()
, thus after returning from the function, this cell might possibly be overwritten by another function.
I don't see how returning a pointer to a local variable (not instanciated on the heap) can ever possibly work.
It doesn't work. It is undefined behaviour. It may seem to work, because "correct behaviour" is a subset of "any possible behaviour".
You're running into undefined behavior, which means anything can happen. Including appearing to work.
Outside the function, the return pointer is dangling (i.e. the memory it points to is invalid).
Why it appears to work boils down to the implementation. Most probably the memory isn't cleared. So although you don't have access to what the return pointer points to, in that memory the 26.48
still exists. But it's just by chance.
double * GetSalary()
{
double salary = 26.48;
return &salary;
}
double dummy_function()
{
double a = 1.1;
double b = 2.2;
double c = 0 , d = 0;
c = a + b - d;
return c;
}
main()
{
double *a;
a = GetSalary();
cout << dummy_function();
cout << *a; //this time it wont print 26.48
}
Because function stack has been overwritten by the second function call dummy_function
It doesn't "work", it's dereferencing a pointer that is no longer valid. That the memory pointed at happens to hold the expected value is not a sign of the program as a whole "working" or being correct.
To understand why it happens to work, you need to analyze the exact pattern of stack frame shifts that take place, which is kind of annoying, and very compiler-dependent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With