0
#include <stdio.h>
int main(){
int i=1;
int * p = &i;
*(p++)=4;

printf("%p\n", p);   //0x7ffc000f47c8  
printf("%u\n", p);   //956816552 (which is 0x7ffc000f47c8 as unsigned integer) 
printf("%u\n", *p);  //956816552 (I would expect *p to be the value of whatever is in 0x7ffc000f47c8, and not the unsigned value of the pointer p (956816552))

return 0;
}

I would expect the printf() of *p to be the value of whatever is in 0x7ffc000f47c8, and not the unsigned value of the pointer p (956816552))

When/How did I set the value of *p to 956816552 (value of p)??

I believe *p++ = 4 isn't UB. (According to the comments of the 1st answer - Undefined behavior and sequence points)

Any help will be much appreciated. Thanks.

Community
  • 1
  • 1
Chloe
  • 47
  • 5
  • 3
    *I believe *p++ = 4 isn't UB* maybe not, but dereferencing p after that is, it's now pointing to memory you don't really own – stijn Mar 24 '16 at 11:43
  • C++ code of conduct: Dereference only if you know the owner. – CinCout Mar 24 '16 at 11:43
  • probably `p` happens to follow `i` in memory, so `p++` leaves `p` pointing to itself. You indeed are seeing "whatever is in 0x7ffc000f47c8" – M.M Mar 24 '16 at 11:59
  • *I would expect *p to be the value of whatever is in 0x7ffc000f47c8, and not the unsigned value of the pointer p (956816552)* Well then, print `*p` **before** you increment it to see what its initial contents are. – Andrew Henle Mar 24 '16 at 12:19

2 Answers2

2

After you perform the increment p++, p can no longer be dereferenced because it no longer points to an object. The program invokes undefined behavior for dereferencing p, at which point we usually say "the program is wrong", fix the program, and move on.

If you are curious about the exact values printed out, the value might be just an accident of what &i+1 happens to point to, or it might be something else.

Note: In this case, the increment itself is well-defined. But if you incremented the pointer again, you would be in trouble, because you've moved past the end of i.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
1

Change the program the following way

#include <stdio.h>
int main(){
int i=1;
int * p = &i;
*(p++)=4;

printf("%p\n", p);   //0x7ffc000f47c8  
printf("%u\n", p);   //956816552 (which is 0x7ffc000f47c8 as unsigned integer) 
printf("%d\n", i);  //956816552 (I would expect *p to be the value of whatever 
       ^^^^^^^^^
is in 0x7ffc000f47c8, and not the unsigned value of the pointer p (956816552))

return 0;
}

and you will see that i was shanged.

After statement

*(p++)=4;

pointer p was changed and points now beyond the variable x So you may not dereference the pointer.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335