0
#include <stdio.h>

int *call();


int main() {

    int *ptr, a = 5;
    ptr = call();

    printf("%d\n", a);
    printf("%d", *ptr);
    return 0;
}

int * call() {
    int x = 25;
    ++x;

    return &x;
}

the above code outputs garbage value after printing the value of a.. but if i remove the printf("%d\n",a); statement then it outputs the value of x. please explain... according to concept of dangling pointer, output should be garbage value . i'm using gcc compiler.

John Ledbetter
  • 13,557
  • 1
  • 61
  • 80
  • It looks like the value of `x`, but it is garbage. – Pascal Cuoq Jan 28 '14 at 18:54
  • it always prints the value of x that is 26...if i remove printf statement(printf("%d\n",a);). – user3245825 Jan 28 '14 at 18:58
  • Duplicate of: http://stackoverflow.com/q/3127507/912144, http://stackoverflow.com/q/19808553/912144, http://stackoverflow.com/q/8743411/912144, http://stackoverflow.com/q/4570366/912144, http://stackoverflow.com/q/15903499/912144 and many others. – Shahbaz Jan 28 '14 at 19:14

2 Answers2

1

What actually happened is call to the first printf overwrote the location where ptr is pointing.

The reason is you returned a pointer to a variable that then went out of scope.

This is undefined behavior.

Don't do that.

Joshua
  • 40,822
  • 8
  • 72
  • 132
0

Applying * operator to an indeterminate pointer (pointing anywhere) invokes undefined behavior. You may get anything. You are getting 26 possibly because after the call of call, 26 is stored in execution stack. *ptr takes that value from the stack.

haccks
  • 104,019
  • 25
  • 176
  • 264