Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting / accessing same memory are as different variables in C

Tags:

c

pointers

memory

If I have 4 bytes of memory and would like to access this memory as both unsigned long L and char c[4]. What would be the most efficient way to do this in C?

For example, if I set the L to 300 then the bytes will be set to 0x0000012c, if I access the c[3] I would expect to see 0x2c

If I increase c[3] by one, it becomes 0x2d and L now has a value of 301

Thanks

like image 417
Don Avatar asked Sep 21 '21 20:09

Don


2 Answers

You can create a union of the two types:

union u1 {
    unsigned long l;
    char c[sizeof(unsigned long)];
};

Then if you create a variable of the union type, you can write to one member and read the other.

Keep in mind however that the result depends on the endianness of your system. Most x86 based systems are little-endian, meaning the least significant byte comes first. If that's the case, the c[0] member would actually have the value 2c.

like image 74
dbush Avatar answered Sep 30 '22 06:09

dbush


You could investigate the memory using a union and type punning:

#include <stdint.h>
#include <stdio.h>

typedef union {
    uint32_t L;
    char c[sizeof(uint32_t)];
} foo;

int main() {
    foo x;
    x.L = 123;
    printf("%X %X %X %X\n", x.c[0], x.c[1], x.c[2], x.c[3]);
}

The output will probably be 7B 0 0 0 or 0 0 0 7B depending on the endianess of your machine.

like image 24
Ted Lyngmo Avatar answered Sep 30 '22 07:09

Ted Lyngmo