• edited by
2,133 views
0 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?

3 Answers

Best answer
0 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 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 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
Position:
Show:

Related questions

0 0 votes
1 1 answer
1.7k
1.7k views
Psnjit asked Jan 12, 2019
1,707 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 0 votes
1 1 answer
1.8k
1.8k views
Mr khan 3 asked Nov 3, 2018
1,835 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 0 votes
1 1 answer
1.6k
1.6k views
sushmita asked Sep 30, 2018
1,552 views
What is the interpretation of following C declaration:char *(*( foo[][8])())[];(A) foo is array of 8 pointer to pointer to function returning pointer to array of pointer ...