This is a very basic question about the scope of a variable suppose. I have the fiollowing code:
int main()
{
int *p;
p=func();
printf("%d",*p);
return 0;
}
int *func()
{
int i;
i=5;
return &i;
}
My question
- The scope of i is finished in
func()but, since I am returning the address ofiwill I be able to access andprint5 inmain()? - If not, why? does the compiler puts a garbage value in that address space (I don’t think this is done).
- What actually it means by
the scope of a variable is ended? Also does the memory allocated toiis freed when its scope ends?
Scope of the variable is the region where it can be accessed.
Lifetime of the variable is the time till when the variable is guaranteed to exist.
In your case lifetime of
iis within the function not beyond it. It meansiis not guaranteed to exist beyond the function. It is not required to and it is Undefined Behavior to access a local variable beyond the function.You might, but it is Undefined Behavior. So don’t do it.
The compiler may put whatever it chooses to in that location, once the function returns the address location is holds an Indeterminate value.
iis a automatic/local variable and all automatic variables are freed once the scope{,}in which they are declared ends. Hence the name automatic.