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.

+3


source to share


2 answers


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.

+4


source


int k = 35;

      



is local to the function fun()

, so as soon as you return from the fun()

memory allocated for k

is no longer valid and you return &k

(the address of that variable), which will result in undefined behavior

0


source







All Articles