3

I am not able to understand an example in Let us C by Yashwant Kanetkar. Here is the code snippet:

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 am not able to understand why having a function call before the printf statement results in printing a garbage value. I have a vague idea that as the returned value points to a memory location in the stack, something goes wrong when another function is called before printing this value. But I am not able to clearly visualize what happens here. Please help.

Mark
  • 626
  • 5
  • 20

2 Answers2

4

in your code

int *fun()
{
    int k = 35;
    return (&k);
}

you're returning the address of a local variable from fun(). Any usage of the return value leads to undefined behaviour.

To explain, once the function fun() finishes execution, there is no existence of k. So , trying to use something like &k is invalid.

Note: Whatever the explanation is provided in that particular book [related to stack flushing or so], is not standardized in c.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0
int k = 35;

is local to function fun() so once you return from fun() the memory allocated for k is no more valid and you are returning &k(address of that variable) which will lead to undefined behavior

Gopi
  • 19,784
  • 4
  • 24
  • 36