Skip to content

Instantly share code, notes, and snippets.

@arsaccol
Created May 2, 2021 06:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arsaccol/182fc244983069bc51d7b31373b2b43b to your computer and use it in GitHub Desktop.
Save arsaccol/182fc244983069bc51d7b31373b2b43b to your computer and use it in GitHub Desktop.
Memory alignment demonstration thingie
#include <stddef.h>
#include <stdio.h>
#define STR(x) #x
typedef struct
{
// === funny little waste of memory due to alignment (or lack thereof) ===
// my CPU can only address bytes in multiples of four
// using a non-multiple of 4 number of bytes for the "name" field makes
// age be placed in the next offset that is a multiple of 4, namely 20 in this case
char name[17];
int age;
} Person;
int main()
{
Person old_dude = {"Very old dude", 123};
Person* pointer_to_dude = &old_dude;
unsigned char* dude_as_byte_array = (unsigned char*)pointer_to_dude;
size_t offset_of_age_in_bytes = offsetof(Person, age);
int dudes_age = *(dude_as_byte_array + offset_of_age_in_bytes);
printf("%s: %lu\n", STR(offset_of_age_in_bytes), offset_of_age_in_bytes);
printf("Dude's age is %d\n", dudes_age);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment