0

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?

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

but everytime i run i get 12,garbage value.it return 12 for the first printf everytime.i don't get that.i even compiled and ran it on TC,it gives the same answer 12 for the first printf and then a garbage value?
@ishansoni - that's what undefined behaviour is - you really don't know what happens, who else changes this memory, what could happen when you try to change it, or if you dereference the pointer i.
i read somewhere that in TC garbage collector is called after a printf statement so maybe thats why.
4

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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.