How to read / write type values ​​from "raw" memory in C?

How do I do something like this work?

void *memory = malloc(1000); //allocate a pool of memory *(memory+10) = 1; //set an integer value at byte 10 int i = *(memory+10); //read an integer value from the 10th byte 
+7
source share
3 answers

A simple example: treat memory as an array of unsigned char

 void *memory = malloc(1000); //allocate a pool of memory uint8_t *ptr = memory+10; *ptr = 1 //set an integer value at byte 10 uint8_t i = *ptr; //read an integer value from the 10th byte 

You can also use integers, but then you should pay attention to the number of bytes that you set immediately.

+6
source

The rules are simple:

  • each type of pointer (except function pointers) can be dropped to and from void * without loss.
  • you cannot do pointer arithmetic on void * pointers and you cannot dereference them
  • sizeof (char) is 1, by definition; therefore incrementing the char pointer means "adding 1" to the "raw" value of the pointer

From this, you can conclude that if you want to perform raw pointer arithmetic, you must cast to and from char *.

+4
source

So, by "work" I assume that you mean "how do I dereference / perform arithmetic on a pointer to void* "? You can not; you should cast it, usually on char* , if you just need to read pieces of memory. Of course, if this is the case, just declare it as char* for starters.

+3
source

All Articles