0

What is the value of q after the following code executes? m' is stored in memory starting at byte 2 and no problems with memory.

int m = 44;
int* p = &m;
int n = (*p)++;
int* q = p - 1;
++*q;

When I execute this code on gcc, the code initializes the memory pointed to by q to 1606417464 and then the last line changes it to 1606417465. This makes sense to me as this block of memory has not been assigned a value.

When I execute this code on my mac using xtools, the memory pointed to by q is initialized as zero and then changes to 1 after ++*q. Any idea why this behavior occurs?

Ira
  • 35
  • 2

1 Answers1

0

Your code invokes undefined behaviour when you try to modify *q (as in ++*q).

int m = 44; // Let's say &m is 1000.
int* p = &m; //  p is 1000 now.
int n = (*p)++; // assigns 45 to 'n'.
                // Now *p (which is 'm') becomes 45.
                // Note p is not modified here but only *p is modified.
int* q = p - 1; // q is 996 or 1004 (depending on which side stack grows)
                //  and assumes sizeof(int*) == 4
                // which may or may not a valid address and may not belong
                // to your program.
++*q; // Here you are essentially modifying some random memory.
P.P
  • 117,907
  • 20
  • 175
  • 238