user50533
user50533

Reputation: 33

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

Upvotes: 3

Views: 5827

Answers (2)

Francesco Garbin
Francesco Garbin

Reputation: 61

For a clearner approach you want to consider the use of reinterpret_cast<> and some form of encapsulation.

With reinterpret_cast<> you can access your address as such:

#define LOCATION 0x28fed8
*reinterpret_cast<DWORD64*>(LOCATION) = 1;

For cleaner code and compiler optimizazion I would encapsulate the memory access instruction into a volatile function inside an anonymous namespace, such as:

namespace {
    volatile DWORD& memory(const DWORD location) {
        return *reinterpret_cast<DWORD64*>(location);
    }
}

and then set my memory location with:

memory(LOCATION) = 1;

or read it with:

std::cout << memory(LOCATION);

Upvotes: 1

tangrs
tangrs

Reputation: 9930

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)

Upvotes: 4

Related Questions