pointers-memory · advanced · ~15 min
Understand memory alignment and implement tagged pointer compression techniques.
Pointers to heap structures aligned on 8-byte boundaries always have their lowest 3 bits set to 000. Tagged pointer architectures exploit this alignment to pack type tags (such as integer vs pointer vs float) into the lowest bits without allocating extra metadata.
Given the 2-bit tag type:
typedef enum {
TAG_RAW_PTR = 0, // bits 00
TAG_STRING = 1, // bits 01
TAG_INT_OBJ = 2, // bits 10
TAG_FLOAT = 3 // bits 11
} PointerTag;
Implement tagged pointer packing:
uintptr_t tag_pointer(const void *ptr, PointerTag tag);
void *untag_pointer(uintptr_t tagged);
PointerTag get_pointer_tag(uintptr_t tagged);
tag_pointer:ptr to uintptr_t.((uintptr_t)ptr & 0x03) != 0, return 0 (alignment violation: pointer is not 4-byte aligned).tag (which is 0..3) into the lowest 2 bits: ((uintptr_t)ptr) | (tag & 0x03).untag_pointer:tagged & ~((uintptr_t)0x03).void * and return it.get_pointer_tag:(PointerTag)(tagged & 0x03).int x = 42; // assume aligned at 0x1000
uintptr_t t = tag_pointer(&x, TAG_STRING); // 0x1001
get_pointer_tag(t); // returns TAG_STRING
untag_pointer(t); // returns &x (0x1000)
ptr: pointer to align; tag: PointerTag enum; tagged: uintptr_t encoded value.
Returns encoded uintptr_t, decoded pointer, or extracted PointerTag.
Pointers must be at least 4-byte aligned (& 0x03 == 0). Use uintptr_t.
#include <stdint.h>
typedef enum {
TAG_RAW_PTR = 0,
TAG_STRING = 1,
TAG_INT_OBJ = 2,
TAG_FLOAT = 3
} PointerTag;
uintptr_t tag_pointer(const void *ptr, PointerTag tag) {
(void)ptr; (void)tag;
return 0;
}
void *untag_pointer(uintptr_t tagged) {
(void)tagged;
return 0;
}
PointerTag get_pointer_tag(uintptr_t tagged) {
(void)tagged;
return TAG_RAW_PTR;
}
Casting pointer to int instead of uintptr_t (64-bit truncation); sign-extension issues with masks.
Unaligned pointer returns 0 on tag_pointer; NULL pointer with tag can be encoded and untagged back to NULL.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.