Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How to directly access memory

Tags:

c++

memory

Say I have manually allocated a large portion of memory in C++, say 10 MB.

Say for the heck of it I want to store a few bits around the middle of this region.

How would I get at the memory at that location?

The only way I know of accessing raw memory is using array notation.

like image 295
Cody Smith Avatar asked Dec 01 '25 11:12

Cody Smith


2 Answers

And array notation works well for that, as the allocated memory can be seen as a large array.

// Set the byte in the middle to `123`
((char *) memory_ptr)[5 * 1024 * 1024] = 123;

I typecast to a char pointer in case the pointer is of another type. If it's already a char pointer then the typecast isn't needed.


If you only want to set a single bit, see the memory as a giant bit field with 80 million separate bits. To find the bit you want, say bit number 40000000, you must first find the byte it's in and then the bit. This is done with normal division (to find the char) and modulo (to find the bit):

int wanted_bit = 40000000;

int char_index = wanted_bit / 8;  // 8 bits to a byte
int bit_number = wanted_bit % 8;

((char *) memory_ptr)[char_index] |= 1 << bit_number;  // Set the bit
like image 169
Some programmer dude Avatar answered Dec 03 '25 02:12

Some programmer dude


Array notation is just another way of writing pointers. You can use that, or use pointers directly like so:

char *the_memory_block = // your allocated block.
char b = *(the_memory_block + 10); // get the 11th byte, *-operator is a dereference.
*(the_memory_block + 20) = b; // set the 21st byte to b, same operator.

memcpy, memzero, memmove, memcmp and others may also be very useful, like this:

char *the_memory_block = // your allocated block.
memcpy(the_memory_block + 20, the_memory_block + 10, 1);

Of course this code is also the same:

char *the_memory_block = // your allocated block.
char b = the_memory_block[10];
the_memory_block[20] = b;

And so is this:

char *the_memory_block = // your allocated block.
memcpy(&the_memory_block[20], &the_memory_block[10], 1);

Also, one is not safer then the other, they are completely equivalent.

like image 27
rmhartog Avatar answered Dec 03 '25 01:12

rmhartog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!