edited by
1,039 views
0 votes
0 votes
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int * show();
int main()
{
	int *p=show();
	//clrscr();
	printf("%d",*p);
}
int * show()
{
	int x=10;
	/*int *p;
	p=(int *)malloc(4);
	*p=x;*/
	return &x;
}

Here as the $show()$ ends variable $x$ gets destroyed but still I am able to access its value why is it so?

edited by

3 Answers

Best answer
0 votes
0 votes
#include<stdio.h>
int * show();
int main()
{
int *p=show();
printf("%d",*p); //Referring x that is de-allocated now but it's value is still exist on memory(in stack)
printf("%d",*p); //The memory (stack space) which is earlier allocated to show() is overwritten now by above printf so it will print a garbage value
return 0; 
}
int * show()
{
int x=10;
return &x;
} //e

Although scope and lifetime of variable x end as point e but its value is still there on the stack that's why 1st printf gives correct output. But after that, the memory is overwritten so 2nd printf will return a garbage value.

NOTE - GCC compiler returns 10 -2(this is a garbage value) with a Warning: function returns address of local variable.

edited by
0 votes
0 votes

The code doesn't work and gives error in GCC, but works with a warning in ZAPCC. So the compiler you used to run this code is optimised to run through such errors by giving warning(s). Try your code here on different compilers, like here:

https://www.jdoodle.com/c-online-compiler

0 votes
0 votes

@ankit I tired on code blocks and it is working fine there. Just giving a warning. 
Although this is the case of undefined behaviour. It's not always true that it will return the correct value. 

Check this modified code. 

#include<stdio.h>
int * show();
int main()
{
int *p=show();
printf("hello"); ​​​​​​
printf("%d",*p); \\memory is overwritten already. So it will print garbage value 
return 0; 
}
int * show()
{
int x=10;
return &x;
} //e

Related questions

0 votes
0 votes
1 answer
1
Psnjit asked Jan 12, 2019
1,157 views
main(){unsigned int i= 255;char *p= &i;int j= *p;printf("%d\n", j);unsigned int k= *p;printf("%d", k);} Both the outputs are -1. I have even tried with - int i = 255(3rd ...
0 votes
0 votes
1 answer
2
Mr khan 3 asked Nov 3, 2018
1,010 views
#include<stdio.h void fun(int *p,int *q) { p=q; *p=q; } int i=0,j=1; int main() { fun(&i,&j); printf("%d%d",i,j); }What will be the output of i and j in 16-bit C Compiler...
0 votes
0 votes
0 answers
4
garvit_vijai asked Sep 2, 2018
703 views
Please explain the output for the following program: #include<stdio.h>int main() { int i = 100; int *a = &i; float *f = (float *)a; (*f)++; pri...