In context to what is written in this article
http://gribblelab.org/CBootcamp/7_Memory_Stack_vs_Heap.html#sec-6
A key to understanding the stack is the notion that when a function exits, all of its variables are popped off of the stack (and hence lost forever). Thus stack variables are local in nature.
So, all the variables that belong to that function in the stack are popped off, except maybe the value which is being returned to the function( or maybe reallocated for parent function?), or if it is not static.
But this particular program works completely fine.
#include<stdio.h>
int* func()
{
int a=6;
int *b;
b=&a;
printf("in func - %d \n",*b);
return b;
}
void func2()
{
int a,c;
a=99;
c=2*a;
printf("in func 2 - %d \n",c);
}
void main()
{
int *b;
b=func();
func2();
printf("in main - %d",*b);
}
Output:
C:\Users\Shaurya\Desktop>gcc asw.c
C:\Users\Shaurya\Desktop>a
in func - 6
in func 2 - 198
in main - 6
C:\Users\Shaurya\Desktop>
I figured the variables that are allocated by the user(using calloc, malloc,realloc) is accessible to other functions because they are in the heap, as the article says. But if we make a pointer to a local variable which is in the stack, and return that pointer, then also the variable is accessible in other function.