Search code examples
c++pointersgccdev-c++pointer-arithmetic

Running 32bit Orwell Dev-C++ on 32bit Win8 with 64bit CPU - incerementing pointer returns incorrect result


I have the following small piece of code that works without any issues on a 64bit Debian 7:

#include <iostream>
using std::cout;
using std::endl;

int main(int argc, char **argv) {
  int s = 10;
  int q = 100;
  int *myPtr = &s;

  cout << "s = " << s
       << "\n&s = " << &s
       << "\nq = " << q
       << "\n&q = " << &q
       << "\nmyPtr = " << myPtr
       << "\n&myPtr = " << &myPtr
       << "\n*myPtr = " << *myPtr
       << endl;

  myPtr = myPtr + 1; // Go one

  cout << "myPtr = " << myPtr
       << "\n&myPtr = " << &myPtr
       << "\n*myPtr = " << *myPtr << endl;
  return 0;
}

A colleague executed this very same code and got totally different result after the increment of the pointer myPtr. His computer is a 32bit Windows 8 on a 64bit processor. On Win8 we are using the the TDM-GCC 4.8.1 32bit release integrated in Orwell Dev-C++ latest version. On Linux we have GCC 4.7 multiplatform (project in CMake does not specify architecture so I presume the compiled file is 64bit).

I got

myPtr = <address of q>
&myPtr = <address of myPtr; same as before>
*myPtr = 100

but he go

myPtr = <NOT address of q>
&myPtr = <address of myPtr; same as before>
*myPtr = 4096

I am completely baffled by this behaviour. I though I got the pointer arithmetic wrong but I did check online even though I'm pretty sure there is nothing wrong with it (I'll feel stupid if that's not the case :D). I simply tell myPtr to point to the next block with size of an integer (since the pointer is of type integer), which in my case is q.

Any ideas what's going on here?


Solution

  • You are invoking undefined behavior. Your pointer is a pointer to s.

    When you increment it, you are pointing to memory that you did not allocate. The address of the pointer itself did not change obviously, but the memory address it is pointing at did.

    Deferencing that pointer after that just interprets whatever value happens to be at that address as an int. And as I just said, since you did not allocate that memory, it is undefined behavior.