I have created a local variable b
in the function foo()
. This function returns the address of the variable b
. As b
is a local variable to the functionfoo()
, the address of the variable is not supposed to be there as the execution of the function foo()
finishes. I get the following warning message:
C:\Users\User\Documents\C codes\fun.c||In function 'foo':
C:\Users\User\Documents\C codes\fun.c|6|warning: function returns address of local variable [-Wreturn-local-addr]|
But the pointer ptr
of the main()
function successfully receives the address of b
and prints it. As far as I know about stack, the address of the local variable b
should cease to exist after the control of the program returns to the main()
function. But the output proves otherwise.
#include<stdio.h>
int* foo()
{
int b = 8;
return &b;
}
int main()
{
int *ptr;
ptr = foo();
printf("b = %d", *ptr);
return 0;
}
Output:
b = 8