Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a pointer

Tags:

c++

pointers

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.

like image 836
user695652 Avatar asked Jun 21 '12 09:06

user695652


4 Answers

It doesn't work. It is undefined behaviour. It may seem to work, because "correct behaviour" is a subset of "any possible behaviour".

like image 184
juanchopanza Avatar answered Nov 17 '22 01:11

juanchopanza


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.

like image 32
Luchian Grigore Avatar answered Nov 17 '22 01:11

Luchian Grigore


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

like image 2
rashok Avatar answered Nov 17 '22 03:11

rashok


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.

like image 1
unwind Avatar answered Nov 17 '22 03:11

unwind