-7

I have this code:

#include <stdio.h>
#include <math.h>
int *fun();
int main()
{
    int *t;
    t=fun();
    printf("%d\n",*t);
    printf("%d\n",*t);
}
int *fun()
{
    int r=95;
    return(&r);
}

The output shown by this code in codeblocks is

95
-2

I don't get why the second printf() is printing a garbage value. Can someone explain that, please?

Frosted Cupcake
  • 1,909
  • 2
  • 20
  • 42

2 Answers2

1

This is UB, because r is a local variable inside fun(), and if you return the address of a local variable and try to use it in the caller, you're ending up using it after is has expired it's lifetime. In C, it is defined as UB.

FWIW, the address of a variable is not always equivalent to an int or can be converted to a pointer safely, thus it should be int *, at least. In your code,

t=fun();

and

return(&r);

should have given you warnings!!

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0
  1. You return an int* from fun, even though it's declared to return int. Change the declaration to int* fun().

  2. An empty list allows a variable number of arguments. Use int* fun(void); instead.

  3. Undefined behavior is undefined behavior. You try to access memory of a local variable from outside the function, so anything might happen. From the level of the C standard, it's plainly undefined whether the first, second, or no statement at all behaves weirdly (like "printing a garbage value").

Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67