Misaligned pointer access
What you'll learn: How to avoid performance penalties and hardware crashes by ensuring your pointers point to addresses the CPU expects.
The Post Office Analogy
Imagine a post office where mailboxes are built in blocks of four. The mail carrier is optimized to grab one entire block at a time. If you ask for the mail in "Block 0" (slots 0, 1, 2, 3), they can hand it to you instantly.
However, if you ask for a "block" starting at slot 1 (slots 1, 2, 3, 4), the carrier has to perform double the work: they must pull out the first block, pull out the second block, throw away the parts they don't need, and stitch the remaining pieces together. In the world of C, this "stitching together" is called a misaligned access.
Alignment in Memory
Every data type in C has an alignment requirement. On most modern systems, a 4-byte int should start at a memory address divisible by 4. A 2-byte short should start at an even address.
When you use a pointer to read data from an "odd" address that doesn't match the data type's natural boundary, two things can happen:
- The Slowdown: The CPU performs extra cycles to piece the data together, making your code sluggish.
- The Crash: On stricter hardware (like some ARM processors), the program will simply trigger a "Bus Error" and terminate immediately.
How it happens in code
Misalignment usually occurs when you "force" a pointer of one type to look at a buffer of a different type using typecasting.
#include <stdio.h>
#include <stdint.h>
int main() {
char buffer[8] = {0, 1, 2, 3, 4, 5, 6, 7};
// A char pointer can point anywhere (alignment 1)
char *ptr_char = &buffer[1];
// DANGER: We cast a 'char*' to an 'int*'.
// 'buffer[1]' is likely not divisible by 4.
int *ptr_bad = (int *)ptr_char;
// This might crash or be very slow depending on your CPU
printf("Value: %d\n", *ptr_bad);
return 0;
}
How to stay safe
To avoid this, avoid "pointer punning"—casting pointers between unrelated types—unless you are absolutely certain the address is correctly aligned. When working with raw bytes (like reading from a file or network), it is safer to use memcpy to move data into a properly declared variable rather than pointing at it directly with a casted pointer.
Key takeaway
Always ensure a pointer's address is a multiple of the data type's size to avoid performance hits or program crashes.