Why does program runs....it should not since ptr is a dangling pointer
Code:#include<stdio.h>
int main( )
{
int *ptr ;
int *f( ) ;
ptr = f( ) ;
printf ( "%d", *ptr ) ;
return 0;
}
int *f( )
{
int a = 10 ;
return ( &a ) ;
}
Printable View
Why does program runs....it should not since ptr is a dangling pointer
Code:#include<stdio.h>
int main( )
{
int *ptr ;
int *f( ) ;
ptr = f( ) ;
printf ( "%d", *ptr ) ;
return 0;
}
int *f( )
{
int a = 10 ;
return ( &a ) ;
}
Undefined behavior unfortunately does include what one might expect to happen if the program were correct.
variable a was allocated on the stack and function f() is returning a valid address to some location on the stack. The problem is that main() thinks (assumes) the address still points to a valid integer called a. The address is valid, but the contents of that address may or may not change -- and changes are pretty good that the contents of that address will change if there are any other functions calls in main() between f() and printf().
I tried adding a function between f() and printf()...now the contents of *ptr is different(Garbage Value)
So what's your question?
How you were lucky in the first example
Or how you were unlucky in the 2nd example
Dave's answer is spot on.
try this code out:
output when i run it is:Code:#include<stdio.h>
void abc(void);
int main( )
{
int *ptr ;
int *f( ) ;
ptr = f( ) ;
abc();
printf ( "%d", *ptr ) ;
return 0;
}
int *f( )
{
int a = 10 ;
return ( &a ) ;
}
void abc(){
int a = 25;
int b = 35;
}
agarwaga@lc1:/u/agarwaga/c> gcc a6.c
a6.c: In function `f':
a6.c:27: warning: function returns address of local variable
agarwaga@lc1:/u/agarwaga/c> ./a.out
25agarwaga@lc1:/u/agarwaga/c>
Automatic variables are made on the stack. Pointer is a dangling pointer after the function call is over. 25 is output in the program above since the call to abc function also makes an automatic variable which is in the same address as the earlier variable(in the previous function call) was .
You can also see the compiler gives a warning also that you should not return the address of a local variable. Such a use is very bad programming practice and should never be done.