Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I make 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
like image 941
dtech Avatar asked Jul 15 '12 09:07

dtech


2 Answers

Easy example: treat the 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 use integers too, but then you must pay attention about the amount of bytes you are setting at once.

like image 165
ziu Avatar answered Sep 25 '22 01:09

ziu


The rules are simple:

  • every pointer type (except function pointers) can be cast to and from void*, without loss.
  • you cannot perform pointer arithmetic on void* pointers, and cannot dereference them
  • sizeof(char) equals 1, by definition; so incrementing a char pointer means "adding 1" to the "raw" pointer value

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

like image 25
wildplasser Avatar answered Sep 24 '22 01:09

wildplasser