Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store a value at a specific location in the memory?

Maybe this is an easy question question but I would really like to know it for sure.

If I want to store a value, say an int, at a specific address in the memory (at the heap), how do I do it?

Say, I want to store the int value 10 at 0x16. I guess do so by calling new or malloc: int *p=new int(10); and then I want to set the address of the stored value to 0x16. At first I thought just something like &p=0x16 but this doesn't work. I need to do this to store some additional information in front of a certain value in the memory (that was previously assigned memory space by malloc or new).

I am using linux and C++ (but C would work as well).

What I want to achieve is: one process calls malloc with size x and I want to store a certain value (the size) in front of the allocated memory, so I can access the size later (when free is called). Since malloc was called, I know the pointer where the OS assigned space for the value and I just want to store the size of the assigned memory in the 4 bytes in front of the assigned memory. What I do (in the malloc hook that I wrote) is to assign more memory (by an internal mallok call) but I also need to be able to store this size value in the specific location.

I am thankful for all help.

like image 443
Bree Avatar asked Jul 12 '11 08:07

Bree


1 Answers

You can do it like this:

*(int *)0x16 = 10;  // store int value 10 at address 0x16

Note that this assumes that address 0x16 is writeable - in most cases this will generate an exception.

Typically you will only ever do this kind of thing for embedded code etc where there is no OS and you need to write to specific memory locations such as registers, I/O ports or special types of memory (e.g. NVRAM).

You might define these special addresses something like this:

volatile uint8_t * const REG_1 = (uint8_t *) 0x1000;
volatile uint8_t * const REG_2 = (uint8_t *) 0x1001;
volatile uint8_t * const REG_3 = (uint8_t *) 0x1002;
volatile uint8_t * const REG_4 = (uint8_t *) 0x1003;

Then in your code you can read write registers like this:

uint8_t reg1_val = *REG_1; // read value from register 1
*REG_2 = 0xff;             // write 0xff to register 2
like image 55
Paul R Avatar answered Oct 10 '22 16:10

Paul R