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 ) ; }
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 ) ; }
"Service of the poor and destitutes is the service of the God"
Normative Changes to ISO/IEC 9899:1990 in Technical Corrigendum 1
Incompatibilities Between ISO C and ISO C++
Undefined behavior unfortunately does include what one might expect to happen if the program were correct.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
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)
"Service of the poor and destitutes is the service of the God"
Normative Changes to ISO/IEC 9899:1990 in Technical Corrigendum 1
Incompatibilities Between ISO C and ISO C++
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.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
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.