Search code examples
c++pointersmemory-address

Access memory address manually


Is there a way to access memory address manually without the use of pointers or references? Let's say I know that integer is stored at address 0x28fed8 and I want to print that data. I've tried std::cout << (int*)0x28fed8 but it just outputs 0x28fed8. Also it works when I assign address to a pointer like that int* w1= (int*)0x28fed8; for integer but gives strange result for a double variable (2.22064e-313)

#include <iostream>

int main(){
   int a=10;
   int* w1= (int*)0x28fed8;

   double b=100.578;
   double* w2= (double*)0x28fed0;

   std::cout << &a << std::endl;  // output 0x28fed8
   std::cout << *w1 << std::endl; // output 10

   std::cout << (int*)0x28fed8 << std::endl; // output 0x28fed8

   std::cout << &b << std::endl;  // output 0x28fed0
   std::cout << *w2 << std::endl; // output 2.22064e-313

   return 0;
}

Of course the results were accurate when I tested it - it may give different output when someone tries to compile that code


Solution

  • If you want to print the value of the integer at a specific address, you need to do

    std::cout << *(int *)0x28fed8 << std::endl;
    

    So you're dereferencing the pointer instead of printing the pointer value itself.

    As to your double value being wrong, I suspect that's to do with compiler optimisation. Your w2 pointer is being dereferenced before the b variable had its value written. If this is true, you just happened to get lucky with a and w1.

    What if you move your b and a variable out to a global variable or mark them as static? This should ensure the value is set by the time the pointers are dereferenced since it's likely to be hardcoded at compile time.

    Otherwise, try making your pointers volatile - i.e. volatile double *w2 and volatile int *w1 so the compiler won't try to optimise.

    (I should mention that overall, your code seems pretty dodgy to begin with. However, I'm not actually sure if it invokes undefined behaviour - perhaps some other users can shed some light on this)