0

Possible Duplicate:
Can a local variable’s memory be accessed outside its scope?

double* weird( double a, double b )
{ 
    double c;
    c = pow( a + b, 0.5 );
    return &c;
}

It might be trivial for most of you guys, but I don't see what could go wrong here.

Community
  • 1
  • 1
CloneXpert
  • 246
  • 2
  • 9

3 Answers3

8

This is very wrong because you are returning a pointer to a local variable.

When &c gets returned, the variable c whose scope is the function weird will be destroyed, thus giving you a pointer that points to a random area in your memory. This is undefined behaviour.

alestanis
  • 21,519
  • 4
  • 48
  • 67
2

You declare a local variable c in scope of the function, that variable is not valid any more after you exit the function, so the pointer to that variable doesn't mean anything afterwards.

Faruk Sahin
  • 8,406
  • 5
  • 28
  • 34
  • I understand, but if i use it like this: cout << *weird(2.1,0.2); I get the result, how can that be? – CloneXpert Oct 21 '12 at 18:42
  • 1
    Undefined behaviour means anything can happen. – alestanis Oct 21 '12 at 18:45
  • 1
    @CloneXpert That code (like many other things which appear to work) causes undefined behavior. That means: Anything can happen, including the results you expect. But it can, and often will, also fail catastrophically. (In this case, it probably "works" because you did not call another function in between and thus that piece of memory wasn't overwritten so far.) –  Oct 21 '12 at 18:45
0

As others have said.

variables except static declared in a method or between curly braces{} have local scope.As soon as you get out of it, the variables are destroyed..

If you still want it,use static

static double c;
Anirudha
  • 32,393
  • 7
  • 68
  • 89