#include <stdlib.h>
#include <stdio.h>
int* test()
{
int *p;
if (1)
{
int y = 10;
p = &y;
}
printf("Address = %p\n", p);
printf("Value = %d\n", *p);
return p;
}
int main()
{
int *ptr = test();
printf("Adress on main = %p\n", ptr);
*ptr = 15;
printf("Value on main = %d\n", *ptr);
}
I thought here "y" will be deleted when the "if" scope or "test" function ends and when I try to access to its address I'm gonna get Segmentation Fault but everything was okay and I was even able to change the value in the pointer on main function how is this possible. Why memory of "y" is not deleted. The output was:
Address = 0x7ffe7e84432c
Value = 10
Adress on main = 0x7ffe7e84432c
Value on main = 15