In the below code
ptr1--->ptr--->&c=4
when i print *ptr and **ptr1 both prints value of c i.e 4 everything is fine here, but after initialization of x with *ptr , i read somewhere
that x=*ptr is equivalent to x=*ptr; ptr= ptr 1;
if it's true that means pointer ptr is pointing to a new address but still *ptr and **ptr1 prints the value of c why?
int main(void)
{
int x, c=4, *ptr=&c,**ptr1=&ptr;
printf("\nBefore incrementation ptr points to c\n%p == %p", ptr,&c);
x=*ptr ;
printf("\n%d,%d,%d,%p,%p,%p\n\n", x,*ptr,**ptr1,&c,ptr,ptr1);
return 0;
}
CodePudding user response:
DO NOT DO THIS under normal circumstances... This 'happily' exploits "undefined behaviour" with the code generated by my C compiler. This is BAD PRACTICE, but useful to understand the behaviour you experienced.
int main() {
int x = 123;
int y = 456;
int z = 789;
int *p = &y; // 'p' points at stack variable 'y'...
printf( "%d %d %d\n", p[-1], p[0], p[1] );
return 0;
}
Output:
789 456 123
I repeat: This is for educational purposes only.
CodePudding user response:
My environment : WSL2 with gcc9.3 I add two value to printf to show the address of local variables:
#include <stdio.h>
int main(void)
{
int x, c=4, *ptr=&c,**ptr1=&ptr;
printf("Before incementation ptr points to c\n%p == %p\n", ptr,&c);
x=*ptr ;
printf("ptr:%p\n", ptr);
printf("x:%d\n*ptr:%d\n**ptr1:%d\n&c:%p\nptr:%p\nptr1:%p\n&ptr:%p\n&ptr1:%p\n",
x, *ptr, **ptr1, &c, ptr, ptr1, &ptr, &ptr1);
return 0;
}
And the output is:
Before incementation ptr points to c
0x7fffe4ffe0d0 == 0x7fffe4ffe0d0
ptr:0x7fffe4ffe0d4
x:4
*ptr:4
**ptr1:4
&c:0x7fffe4ffe0d0
ptr:0x7fffe4ffe0d4
ptr1:0x7fffe4ffe0d8
&ptr:0x7fffe4ffe0d8
&ptr1:0x7fffe4ffe0e0
Note that? The "ptr" is adjacent to "c" on stack. So after "x=*ptr ", "ptr" pointing to itself.
if it's true that means pointer ptr is pointing to a new address but still *ptr and **ptr1 prints the value of c why?
So you can see that "ptr" does not pointing to c.
The next problem is when does "*ptr" changed, I'am single-instruction tracing the code, I found it is changed in a piece of pre-call asm-code:
119b: 48 8b 45 e8 mov -0x18(%rbp),%rax
119f: 48 8d 55 e0 lea -0x20(%rbp),%rdx
11a3: 48 89 c6 mov %rax,%rsi
11a6: 48 8d 3d 5b 0e 00 00 lea 0xe5b(%rip),%rdi # 2008 <_IO_stdin_used 0x8>
11ad: b8 00 00 00 00 mov $0x0,