Skip to content

Instantly share code, notes, and snippets.

@komiga
Last active December 1, 2015 00:23
Show Gist options
  • Save komiga/27d4e610104d1ad75b4c to your computer and use it in GitHub Desktop.
Save komiga/27d4e610104d1ad75b4c to your computer and use it in GitHub Desktop.
Example of memory addressing in C
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
struct S {
// This is complicated by padding, but:
// NB: sizeof(int32_t) = 4 bytes (32 bits)
// base_address + 0
int32_t x;
// base_address + sizeof(x) = base_address + 4
int32_t y;
};
int main() {
struct S s = {
.x = 0xAAAAAAAA,
.y = 0xBBBBBBBB,
};
// These two accesses are compiled down to:
// (int32_t*)(&s + 0)
// (int32_t*)(&s + 4)
// The "constant offsets" here are 0 and 4, which are calculated from
// the structure of S at compile time -- not determined at runtime.
printf(
"%8x\n"
"%8x\n",
s.x,
s.y
);
// Or, to use the utilities provided by the language in C99
// (see http://en.cppreference.com/w/c/types/offsetof)...
// This is effectively equivalent to:
// (size_t)(((struct S*)0)->member)
size_t x_offset = offsetof(struct S, x);
size_t y_offset = offsetof(struct S, y);
int32_t* x_ptr = (int32_t*) ( ((uint8_t*)&s) + x_offset );
int32_t* y_ptr = (int32_t*) ( ((uint8_t*)&s) + y_offset );
printf(
// (base_address + offset) = value
"*(%p + %u) = %8x\n"
"*(%p + %u) = %8x\n",
&s, (unsigned)x_offset, *x_ptr,
&s, (unsigned)y_offset, *y_ptr
);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment