#include <stdio.h>
int main()
{
int *ptr;
{
int x = 2;
ptr = &x;
}
printf("%x %d", ptr, *ptr);
return 0;
}
Output: address of x, value of x.
Here, ptr
should be a dangling pointer, right? Yet, it still stores the address of x
. How is it still pointing the value of x
, even after that block is deleted?
#include <stdio.h>
int * func (int n)
{
int temp;
int *ptr = &temp;
temp = n * n;
return ptr;
}
int main()
{
int n = 4;
int *p = func(4);
printf("%x, %d", p, *p);
return 0;
}
Output: address of temp, 16
In this program, the data variable temp
and its pointer variable ptr
is created in separate function. Why does it produce a correct result?
#include <stdio.h>
int * func (int n)
{
int temp;
int *ptr = &temp;
temp = n * n;
for (int i = 0; i < 10; i++)
printf("%d ", *ptr);
return ptr;
}
int main()
{
int n = 4;
int *p = func(4);
printf("\n%x, %d", p, *p);
for (int i = 0; i < 10; i++)
printf("%d ", *ptr);
*p = 12;
printf("%d\n", *p);
printf("%d\n", *p);
return 0;
}
Output: 16 16 16 16 16 16 16 16 16 16
address of temp, 1
16 16 16 16 16 16 16 16 16 16
12
12
The above program is similar to the second one aside from the for loop. In
the main()
function, it gives the correct output every time. Even if I tried to change it to *p = 10
, it would still give the correct output no matter how many times I print it.
But in the second program, it only gives the correct output once because of undefined behavior. It gives garbage values after the first printf.
But in third program, how does it still give the correct output every time?
My questions are:
Thank you everyone for answering. I underatand now from all your answers. Thank you very much.
I have disassembled your third program by IDA.
The func() function is compiled as a part of the main() function, not compiled as an independent function.
So, the correct values are remained.
I guess this is the optimization result during compiling.
But, When I add one line to func(), the result of program is different.
In this case, the compiler recognized the 'func()' as a function.
The expected result is occurred and the program is crashed at '*p = 12'.