0

What will be the output of the following program?

int *call();

void main() {
  int *ptr = call();
  printf("%d : %u",*ptr,ptr);
  clrscr();
  printf("%d",*ptr);
}

int *call() {
  int x = 25;
  ++x;
  //printf("%d : %u",x,&x);
  return &x;
}

Expected Output: Garbage value
Actual Output: 26 #someaddr

Since x is a local variable it's scope ends within the function call. I found this code as an example for dangling pointer.

3
  • 1
    The program exhibits undefined behavior, for the reason you mention. What is your question? You expected anything and you got something. Commented Oct 17, 2011 at 7:00
  • Sure with: "ptr=call(); " ? Is not "ptr=call; "? Commented Oct 17, 2011 at 7:00
  • 2
    Actually, in this context, 26 is a garbage value. Commented Oct 17, 2011 at 7:53

3 Answers 3

2

its Undefined behaviour

since at x scope is dead after returning from call() so the pointer to that variable you can not use ahaed

BY COMPILING YOUR program you will get following error

warning: function returns address of local variable

if your program since give output 26 since its undefined behaviour. You should no do this at all.

Sign up to request clarification or add additional context in comments.

Comments

1

the output of this function is undefined. As you already pointed out the scope of x ends with the function. But the memory where 26 has been written is not used agian. So printing this value will give 26. If this memory is used again, it could be anything.

Comments

0

Welcome, you have entered the Undefined Behavior valley. You can't predict what would be any value. Even if the value makes some sense, ignore it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.