Search code examples
c++pointerscastingmemory-mapping

Accessing memory mapped register


Assume there is a memory mapped device at address 0x1ffff670. The device register has only 8-bits. I need to get the value in that register and increment by one and write back.

Following is my approach to do that,

In the memory I think this is how the scenario looks like. enter image description here

void increment_reg(){

int c;//to save the address read from memory
char *control_register_ptr= (char*) 0x1ffff670;//memory mapped address. using char because it is 8 bits

c=(int) *control_register_ptr;// reading the register and save that to c as an integer
c++;//increment by one    
*control_register_ptr=c;//write the new bit pattern to the control register
}

Is this approach correct? Many thanks.


Solution

  • Your approach is almost correct. The only missing part - as pointed out in the comments on the question - is adding a volatile to the pointer type like so:

    volatile unsigned char * control_register_ptr = ...
    

    I would also make it unsigned char, since that is usually a better fit, but that's basically not that much different (the only meaningful difference would be when shifting the value down.)

    The volatile keyword signals to the compiler the fact that the value at that address might change from outside the program (i.e. by code that the compiler doesn't see and know about.) This will make the compiler more conservative in optimizing loads and stores away, for example.