local pointer variables
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 #someaddrSince 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.
精彩评论