-2

What happens to the stack frame after a function is called? I have a function that returns the address of a local variable - should I be able to do that, or is the stack frame destroyed after the function is returned? Here is my code - I expected to get the wrong result, but I got the right result instead.

#include<stdio.h>
#include<stdlib.h>
int* sum(int a,int b)
{
int x=a+b;
return &x;
}

int main()
{
int*a;
int x=5,y=6;
a=sum(x,y);
printf("%d",*a);
return 0;
}
prprcupofcoffee
  • 2,950
  • 16
  • 20

2 Answers2

1

In this case x goes out of scope, the value it returns is invalidated, and as such, any reference to it is undefined behaviour. When things fall out of scope it's like returning an address to an apartment you're no longer renting.

As to what happens to the memory, it may or may not be overwritten. It doesn't matter. Using x outside of that scope is problematic and should not be done. This function, in effect, cannot work as designed because the values it produces are useless.

In this trivial example there's really no reason to return a pointer to an int when you could return an int for exactly the same cost.

If you need to return a pointer to a value that's created within the function you must allocate that dynamically so it won't fall out of scope. This also carries with it the implicit requirement that subsequent code owns that pointer and will call free at the appropriate time.

tadman
  • 208,517
  • 23
  • 234
  • 262
0

You should never return a reference to a local variables. Your long-living outer pointer would accept that reference for sure, but the memory to be reclaimed (and overwritten) on the next function call so your pointer is pointing to rubbish.

In your case, just return a value instead of the reference.

Yury Schkatula
  • 5,291
  • 2
  • 18
  • 42
  • I Know that but i am surprised i got a valid answer. – Yousif Dafalla Jun 15 '18 at 15:43
  • 1
    @YousifDafalla The stack frame is not necessarily overwritten immediately. Read [**this**](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794) – Jabberwocky Jun 15 '18 at 15:59