Impossible to understand Let's look at an example of a static C cluster
I cannot understand the example in Let's C by Yashwant Kanetkar. Here's a snippet of code:
main()
{
int *j;
int *fun();
j = fun();
// If we add a function call here, the print statement prints a garbage value.
printf("\n%d",*j);
}
int *fun()
{
int k = 35;
return (&k);
}
Now in the above code, I can't figure out why calling the function before the printf output results in the garbage value being printed. I have a vague idea that since the return value points to a memory location on the stack, something is wrong when another function is called before printing that value. But I cannot clearly imagine what is happening here. Please, help.
source to share
in your code
int *fun()
{
int k = 35;
return (&k);
}
you are returning the address of a local variable from fun()
. Any use of the return value results in undefined behavior .
To explain, once the function fun()
finishes executing, there is no existence k
. So trying to use something like is &k
invalid.
Note. Whatever explanation in this particular book [related to stack flushing or so) is not standardized in c.
source to share