1

This one must be a silly question, but I am not able to understand why this happens

int main()
{
    int i=20;
    int *p=&i;
    cout<<"old p="<<p<<endl;
    *(++p) = 10;
    cout<<"p="<<p<<endl;

}

In this code I get the output as: old p=0x22ff08 p=oxa

Why is the value of the pointer getting changed to 10(0xa) instead of incrementing the earlier address and assign 10 to that location?

sajas
  • 1,599
  • 1
  • 17
  • 39
  • 3
    That *is* undefined behaviour. – chris Oct 17 '12 at 03:34
  • 1
    What do you mean by "incrementing the earlier address and assign 10 to that location"? What result did you expect? – Raymond Chen Oct 17 '12 at 03:37
  • What I thought was that, the pointer variable might point to the new location 0x22ff0C and try to enter the value there. But now I get it. Thanks to R.Martinho. And thank you guys. – sajas Oct 17 '12 at 04:17

3 Answers3

4

Why is the value of the pointer getting changed to 10(0xa) instead of incrementing the earlier address and assign 10 to that location?

To what location? There is no such location. p was pointing to one int, not an array of ints. The pointer that results from such increment does not point to a location that you can perform indirection on. Attempting to do so as this code does has undefined behaviour, meaning absolutely anything can happen. The compiler is free to do whatever it pleases, because there are no requirements on what need to happen. Don't do it.

In your particular experiment, it appears that the two variables were located next to each other, and when incremented, the variable p ended up pointing to itself, and then assigned 10, which is A in hexadecimal. There is no guarantee that this will happen again when you compile with a different compiler version or compiler options, or even if you make seemingly innocent changes to the code. Don't do it.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • Have a look. I used two different versions of the same compiler and got two different results: http://ideone.com/eTnOD and http://liveworkspace.org/code/20bde3a566de683718bf122ef699e7f3. It's not just a matter of getting different outputs. In fact, using the first one, the program *crashed* with a segmentation fault (look at where it says "result: Runtime error [...] (SIGSEGV)") – R. Martinho Fernandes Oct 17 '12 at 03:47
  • I have a replacement for ideone now. With an up to date version of GCC and Boost. Thanks. – Benjamin Lindley Oct 17 '12 at 03:54
1

You are trying to access a location that might be already occupied or is in use by another program/process by incrementing the pointer and you are trying to overwrite that value.

1

by incrementing the pointer by one element, actually you are visiting the same pointer and modifying its value to 0xA since they are located on the memory sequentially.

Alican
  • 286
  • 1
  • 8