Question

I have a question about scope or lifetime of variables, let me explain my question with an example.The code below, I've created a local variable c and returned it. In main() function the line a=foo(), I think since c is a local variable and the function foo() was done, the memory cell for variable c should have been destroyed and the variable a should have been kept garbage value.However it keeps 1. Where am I wrong is there anyone to help me ? Thanks in advance.

#include <stdio.h>
int foo()
{
    int c=1;
    return c;
}


int main()
{
    int a;
    a=foo();
    printf("%d",a);
    return 0;
}
Was it helpful?

Solution

its basically a function activation record,which will be pushed on the system stack and when your function is returning it will first copy all values to the return result area,that is nothing but a=foo(); and then it will destroy that function activation record from the system stack,I hope it would help

OTHER TIPS

It is not necessary to make its value garbage. after function collapse allocated memory is getting freed but its value remain same,it does not overwrite value with another garbage value.

After foo function returns, object c is destroyed. In the return statement, c object is evaluated and its value is returned. What you are returning is not c object but the value of c.

When return c; it copy c to a tmporary value .And the then copy the tmporary value to a

the memory of c was indeed destroyed when the function was done, but the function returned 1 and that 1 was put in a. the value was copied to the memory of a!

but, for example, this next example will not save the value:

#include <stdio.h>
int foo(int a)
{
    int c=1;
    a = c;
}


int main()
{
    int a = 0;
    a=foo();
    printf("%d",a);
    return 0;
}

will print "0"

I think since c is a local variable and the function foo() was done, the memory cell for variable c should have been destroyed

Yes, this is likely what happens.

But, your function returns a value, and in this case 1, the value of c.
So however the variable c is freed, that value is returned, it is not lost or freed.

Then you store that value in a and that is why a = 1.

opps i misunderstood your question in my first reply. actually when you return from any function there are some rules in assembly code.

so it copy value in internal register and then value of this register is copied into a.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top