-3

I am trying to return the value stored in a local variable to the main() function.

#include<stdio.h>
int *func();
int main()
{
    int *ptr;
    ptr = func();
    printf("%d", *ptr);
    printf("%d", *ptr);
    return 0;
}

int *func()
{
    int x = 5, *p;
    p = &x;
    return p;
}

The first printf() statement gives output = 5, but the second printf() statement gives a garbage value as output.

I know that the local variable 'x' will not exist after the function "func()" terminates. Then why is it printing 5 for the first printf() statement?? Please tell me what is happening inside the code.

Dhaval Pankhaniya
  • 1,996
  • 1
  • 15
  • 26

1 Answers1

3

When func is invoked, it creates a stack for its local variables x and p. However, when it returns, this stack is destroyed. Therefore, p points a value that has already been destroyed, so its behavior is undefined.

Jared Cleghorn
  • 551
  • 5
  • 8