-2
int *something() {
    int x = 5;
    int *b = &x;
    return b;

}

int main() {
    int z = *something()
    printf("%d",z);

}

how does this work if the function called something is allocated on stack then the int x and int *b are removed after the it returns a value

if they were removed we wouldn't be able to deference the pointer returned by something because what it pointed to was int x which was deleted from stack

Charana
  • 1,074
  • 1
  • 13
  • 26
  • 3
    Undefined behaviour. – Oliver Charlesworth Nov 07 '15 at 10:51
  • 2
    I'm voting to close this question as off-topic because UB dup*1000 – Martin James Nov 07 '15 at 10:54
  • 2
    Before this question is inevitably closed... Basically you have the intuition right here, this won't work reliably (for exactly the reason you gave) and is undefined behaviour in C. That it might have worked for you this one time is a fluke, likely your compiler inlined the whole function and just constant propagated z = 5; – James Greenhalgh Nov 07 '15 at 10:57
  • 5
    Some relevant answers: [Undefined, unspecified and implementation-defined behavior](http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) and [does undefined behavior really permit **anything** to happen?](http://stackoverflow.com/questions/32132574/does-undefined-behavior-really-permit-anything-to-happen) – kaylum Nov 07 '15 at 10:58

3 Answers3

0

Your problem is that x is a temporary variable and when it goes out of scope at the end of something(), although b is pointing to its address, b will then point to undefined memory when x goes out of scope, and dereferencing it will cause undefined behaviour.

Joe
  • 31
  • 3
0

The post appears to be asking why this works at all. The answer is that, yes, the local variables are no longer meaningful after something exits, but the pointer still points to something. It points to a bit of memory that might contain anything. So you will get some output. It just doesn't mean anything.

Tom Zych
  • 13,329
  • 9
  • 36
  • 53
0

The function itself is not allocated in the stack.

It has two local variables x and b.

The function returns a pointer to its local variable x that after exiting the function is considered as is not alive.

However until the memory occupied by the variable will not be rewritten the value of the variable can be present there.

So variable z can get its value.

However in general it is an undefined behaviour.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335