ishan soni
ishan soni

Reputation: 92

Can't understand the output of this code stack storage function call c

I had the following code, however I don't understand what and why it outputs what it does.

int main(){
   int *i;
   int *fun();
   i=fun();
   printf("%d\n",*i);
   printf("%d\n",*i);
}

int *fun(){ 
   int k=12;
   return(&k);
}

The output is 12 and a garbage value. Can somebody explain the output?

Shouldn't it return garbage values both times?

I know that k is local to fun(), so it would be stored on a stack and that it would be destroyed when fun() goes out of scope. What concept am I missing here?

Upvotes: 0

Views: 74

Answers (2)

Kiril Kirov
Kiril Kirov

Reputation: 38173

Wouldn't it return garbage values both of the time?

After the return of fun, k does not exist anymore, so printing the value, stored in the address of k is undefined behaviour.

That's why you have different/garbage value.

k is local to fun(), so it would be stored on a stack and that activation would be destroyed when the fun ends, or am I missing some concept?

You're not missing anything, except the fact, that the stack isn't immediately "annulled", or something like this. In other words, after the return of fun, the compiler's free to do whatever it wants with this memory.

Upvotes: 5

shf301
shf301

Reputation: 31394

The stack isn't immediately cleared when a function returns, so the 12 will still be on the stack after fun() returns - until something else overwrites it.

You'll see different results in different compilers and different build options (debug vs. release).

Upvotes: 4

Related Questions