开发者

local pointer variables

开发者 https://www.devze.com 2023-04-13 06:05 出处:网络
What will be the output of the following program? int *call(); void main() { int *ptr = call(); printf(\"%d : %u\",*ptr,ptr);

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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号