A sample program trying to access stack memory after the function it belongs to has returned.
#include<stdio.h>
int* testing()
{
int i=5;
int *ptr=&i;
return ptr;
}
int main()
{
printf("%d\n",*(testing()));
return 0;
}
There won't be any compilation error but the output of the program will be unpredictable.
Now lets do
#include<stdio.h>
void printMem(int *ptr)
{
printf("%d\n",*ptr);
}
void testing()
{
int i=5;
int *ptr=&i;
printMem(ptr);
}
int main()
{
testing();
return 0;
}
ya you judged it right, its ok. It will print 5 every time, because the address of i is still in the scope of the process. While in case of first program it was not.
Lets look at this program
Here the output will be correct and that is 5. Why?, because test function is returning the address of the static variable.
Static variable lies in the data segment of the process. Once a static variable is created it remains in the process memory throughout its life span.
lets look in another program
#include<stdio.h>
int main()
{
int *ptr;
{
int i=5;
ptr=&i;
}
printf("%d\n",*ptr);
return 0;
}
This will also result in unpredictable result WHY??????? this is for you :)
#include<stdio.h>
int* testing()
{
int i=5;
int *ptr=&i;
return ptr;
}
int main()
{
printf("%d\n",*(testing()));
return 0;
}
There won't be any compilation error but the output of the program will be unpredictable.
Now lets do
#include<stdio.h>
void printMem(int *ptr)
{
printf("%d\n",*ptr);
}
void testing()
{
int i=5;
int *ptr=&i;
printMem(ptr);
}
int main()
{
testing();
return 0;
}
ya you judged it right, its ok. It will print 5 every time, because the address of i is still in the scope of the process. While in case of first program it was not.
Lets look at this program
Here the output will be correct and that is 5. Why?, because test function is returning the address of the static variable.
Static variable lies in the data segment of the process. Once a static variable is created it remains in the process memory throughout its life span.
lets look in another program
#include<stdio.h>
int main()
{
int *ptr;
{
int i=5;
ptr=&i;
}
printf("%d\n",*ptr);
return 0;
}
This will also result in unpredictable result WHY??????? this is for you :)
No comments:
Post a Comment