Theory-Pointer Casting and Alignment in Embedded C: Strict Aliasing, Endianness and Packed Structures-Free Embedded C Tutorial

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

MODULE 9 · LESSON 9.5 · THEORY

Pointer Casting and Alignment in Embedded C: Strict Aliasing, Endianness and Packed Structures

What a pointer cast does, natural alignment and the Cortex-M4 unaligned rules, structure padding, strict aliasing and safe type punning, little- and big-endian layouts, byte-buffer field access, packed structs and uintptr_t. Keep this in mind whenever you apply pointer casting and alignment in embedded C.

60 min
Read Time
Intermediate → Advanced
Level
M9 · L5
Module / Lesson

What You Will Learn

✓ What a pointer cast does (and does not do) to the data
✓ Natural alignment and what the Cortex-M4 does with unaligned accesses
✓ Structure padding and _Alignof
✓ The strict aliasing rule and the safe alternatives: memcpy, unions and byte pointers
✓ Little-endian versus big-endian and where byte order matters
✓ Reading and writing multi-byte fields from byte buffers with shifts
✓ Packed structures and the unaligned-pointer trap
✓ Integer-to-pointer casts, uintptr_t and the Thumb bit

Key Terms

CastAlignmentPaddingStrict aliasingEndiannessLittle-endianBig-endianByte swapPacked structType punningunionmemcpyuintptr_tUsageFaultUnaligned access

1. What a Pointer Cast Really Does

A cast between pointer types changes only how the compiler interprets the address; no data is converted. After (uint16_t *)p the same address is read as 16-bit values. This is different from a cast between arithmetic types, where the value itself is converted ((int)3.7 is 3). Many bugs in pointer casting and alignment in embedded C start here.

cast_meaning.c
#include <stdio.h> #include <stdint.h> #include <string.h> int main(void) { float f = 1.0f; int converted = (int)f; /* arithmetic cast: the VALUE is converted */ uint32_t bits; _Static_assert(sizeof bits == sizeof f, “sizes must match”); memcpy(&bits, &f, sizeof bits); /* reinterpretation of the BYTES (the safe way) */ printf(“(int)1.0f = %d\n”, converted); printf(“bits of 1.0f = 0x%08X\n”, (unsigned)bits); const uint8_t *bytes = (const uint8_t *)&f; /* a pointer cast: same memory, different view */ printf(“first byte of f = 0x%02X, last byte = 0x%02X\n”, bytes[0], bytes[3]); return 0; }
Output (verified by compiling and running)
(int)1.0f = 1 bits of 1.0f = 0x3F800000 first byte of f = 0x00, last byte = 0x3F

The 32-bit pattern of the float 1.0 is 0x3F800000; in little-endian memory the last byte (the one at the highest address) holds 0x3F. A cast never fixes alignment or byte order: it only changes the type the compiler assumes. This is the core rule of pointer casting and alignment in embedded C.

CastEffectRisk
(uint8_t *)p from any object pointerView the object as bytesSafe: character types may alias anything
(uint32_t *)bytesView bytes as wordsAlignment fault, strict aliasing violation
(T *)void_ptrRestore the real typeSafe if the original type was T
(int *)const_ptrRemove constUndefined if the object is really const
(volatile uint32_t *)0x40020C14Make a register pointerRight address and width are your responsibility
Function pointer to another signatureCall through a wrong typeUndefined behavior

2. Alignment

Every type has an alignment: the address of an object of that type should be a multiple of this number. The usual rule is natural alignment, alignment equal to the size, up to the maximum the machine needs. Hardware reads are fastest, and sometimes only possible, when the address is naturally aligned. Reviewers check pointer casting and alignment in embedded C closely.

alignment.c
#include <stdio.h> #include <stdint.h> #include <stddef.h> int main(void) { printf(“type size align\n”); printf(“uint8_t %4zu %5zu\n”, sizeof(uint8_t), _Alignof(uint8_t)); printf(“uint16_t %4zu %5zu\n”, sizeof(uint16_t), _Alignof(uint16_t)); printf(“uint32_t %4zu %5zu\n”, sizeof(uint32_t), _Alignof(uint32_t)); printf(“uint64_t %4zu %5zu\n”, sizeof(uint64_t), _Alignof(uint64_t)); printf(“double %4zu %5zu\n”, sizeof(double), _Alignof(double)); struct S { uint8_t a; uint32_t b; uint8_t c; }; /* members in this order */ printf(“struct {u8, u32, u8}: size %zu, align %zu, offsets a=%zu b=%zu c=%zu\n”, sizeof(struct S), _Alignof(struct S), offsetof(struct S, a), offsetof(struct S, b), offsetof(struct S, c)); return 0; }
Output (verified by compiling and running)
type size align uint8_t 1 1 uint16_t 2 2 uint32_t 4 4 uint64_t 8 8 double 8 8 struct {u8, u32, u8}: size 12, align 4, offsets a=0 b=4 c=8

The structure has 6 bytes of data but occupies 12: the compiler inserts 3 padding bytes after a so that b starts at offset 4, and 3 more after c so that an array of these structures keeps every b aligned. The same layout results on the Cortex-M4 (all of these types have the same size and alignment there; only 64-bit types have alignment 8 on both). Interviewers test pointer casting and alignment in embedded C on exactly this point.

struct {uint8_t a; uint32_t b; uint8_t c;}
a
off 0
pad
1
pad
2
pad
3
b
off 4..7
c
off 8
pad
9
pad
10
pad
11

What the Cortex-M4 does with an unaligned address

AccessAlignedUnaligned
LDR/STR, LDRH/STRH (single word or half-word)One bus transferAllowed on Cortex-M3/M4 (several transfers, slower), unless the UNALIGN_TRP bit in the CCR register is set
LDM, STM, LDRD, STRD, PUSH/POP multipleNormalUsageFault (UNALIGNED)
Exclusive accesses LDREX/STREXNormalUsageFault
Floating-point VLDR/VSTRNormalUsageFault (not word-aligned)
Cortex-M0/M0+NormalHardFault for any unaligned word/half-word

Because the compiler may turn a loop over a uint32_t * into LDM instructions, code that happens to work with unaligned pointers at -O0 can fault at -O2 or move to another core. The only portable rule: never form a wider pointer from an address that is not aligned for it. Master pointer casting and alignment in embedded C by practising this case.

DMA and peripherals: The STM32 DMA controller also requires aligned addresses for its configured data width (a half-word transfer needs an even address). A misaligned buffer address silently gives wrong data or an error flag.

3. Strict Aliasing

C assumes that a pointer to one type does not point to an object of an unrelated type (the strict aliasing rule). Reading a float object through a uint32_t * violates it; the compiler is then allowed to assume that the two accesses are independent, reorder them or remove them. The exception is access through a character type: char, signed char and unsigned char (and thus uint8_t) may inspect any object. Remember this when you review pointer casting and alignment in embedded C in code reviews.

pun.c
#include <stdint.h> uint32_t float_bits(float f) { return *(uint32_t *)&f; /* reads a float object as uint32_t */ }
GCC detects a type-punning pointer cast
pun.c: In function ‘float_bits’: pun.c:5:13: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing] 5 | return *(uint32_t *)&f; /* reads a float object as uint32_t */ | ^~~~~~~~~~~~~~

There are three well-defined ways to reinterpret bytes:

safe_pun.c
#include <stdio.h> #include <stdint.h> #include <string.h> /* 1. memcpy: always legal; the compiler turns it into a register move */ static uint32_t bits_memcpy(float f) { uint32_t u; memcpy(&u, &f, sizeof u); return u; } /* 2. union: legal in C99/C11 (type punning through a union member) */ static uint32_t bits_union(float f) { union { float f; uint32_t u; } x = { .f = f }; return x.u; } /* 3. byte pointer: legal, assembles the value byte by byte (little-endian here) */ static uint32_t bits_bytes(float f) { const uint8_t *b = (const uint8_t *)&f; return (uint32_t)b[0] | ((uint32_t)b[1] << 8) | ((uint32_t)b[2] << 16) | ((uint32_t)b[3] << 24); } int main(void) { float samples[] = { 1.0f, –2.0f, 0.5f }; for (int i = 0; i < 3; i++) printf(“%5.1f -> memcpy 0x%08X union 0x%08X bytes 0x%08X\n”, samples[i], (unsigned)bits_memcpy(samples[i]), (unsigned)bits_union(samples[i]), (unsigned)bits_bytes(samples[i])); return 0; }
Output (verified by compiling and running)
1.0 -> memcpy 0x3F800000 union 0x3F800000 bytes 0x3F800000 -2.0 -> memcpy 0xC0000000 union 0xC0000000 bytes 0xC0000000 0.5 -> memcpy 0x3F000000 union 0x3F000000 bytes 0x3F000000

All three agree. Prefer memcpy: it is correct for any types, safe with respect to alignment, and compiles to a single register transfer at -O1 and above on ARM. (Compiling with -fno-strict-aliasing hides the problem, but costs optimisation and does not fix alignment.)

4. Endianness

Endianness is the order in which the bytes of a multi-byte value are stored. In little-endian storage the least significant byte has the lowest address; in big-endian the most significant byte comes first. The Cortex-M4 (and x86) is little-endian. Many protocols and file formats are big-endian (“network byte order”): TCP/IP, Modbus registers, many sensor data sheets.

0x12345678 at address A
little-endian
A+0: 78
A+1: 56
A+2: 34
A+3: 12
big-endian
A+0: 12
A+1: 34
A+2: 56
A+3: 78
endian.c
#include <stdio.h> #include <stdint.h> static uint32_t swap32(uint32_t v) { return (v >> 24) | ((v >> 8) & 0x0000FF00u) | ((v << 8) & 0x00FF0000u) | (v << 24); } int main(void) { uint32_t v = 0x12345678u; const uint8_t *p = (const uint8_t *)&v; printf(“memory order : %02X %02X %02X %02X\n”, p[0], p[1], p[2], p[3]); printf(“this machine : %s-endian\n”, p[0] == 0x78 ? “little” : “big”); printf(“swap32 : 0x%08X\n”, (unsigned)swap32(v)); return 0; }
Output (verified by compiling and running)
memory order : 78 56 34 12 this machine : little-endian swap32 : 0x78563412

On the Cortex-M4 the CMSIS intrinsic __REV(x) does the swap in one instruction (REV), and __REV16 swaps the bytes inside each half-word. GCC also offers __builtin_bswap32 which compiles to the same instruction. The portable shift version above is recognised by GCC and also becomes a single REV at -O2.

5. Reading Multi-Byte Fields from a Byte Buffer

The right way to extract an integer from a received frame does not depend on the host’s byte order or alignment: build it from bytes with shifts. The function states the wire format explicitly.

field_access.c
#include <stdio.h> #include <stdint.h> static uint16_t rd_u16_be(const uint8_t *p) { return (uint16_t)((p[0] << 8) | p[1]); } static uint16_t rd_u16_le(const uint8_t *p) { return (uint16_t)((p[1] << 8) | p[0]); } static uint32_t rd_u32_be(const uint8_t *p) { return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3]; } static void wr_u32_be(uint8_t *p, uint32_t v) { p[0] = (uint8_t)(v >> 24); p[1] = (uint8_t)(v >> 16); p[2] = (uint8_t)(v >> 8); p[3] = (uint8_t)v; } int main(void) { /* a frame: 1 type byte, then a 16-bit big-endian value and a 32-bit big-endian value; the fields start at odd addresses, so casting to uint16_t * or uint32_t * would be misaligned */ uint8_t frame[7] = { 0x42, 0x01, 0x2C, 0x00, 0x01, 0x86, 0xA0 }; printf(“type = 0x%02X\n”, frame[0]); printf(“u16 big-end = %u\n”, rd_u16_be(&frame[1])); /* 0x012C = 300 */ printf(“u16 little-end= %u (same bytes, other convention)\n”, rd_u16_le(&frame[1])); printf(“u32 big-end = %lu\n”, (unsigned long)rd_u32_be(&frame[3])); /* 0x000186A0 = 100000 */ uint8_t out[4]; wr_u32_be(out, 100000u); printf(“encoded 100000: %02X %02X %02X %02X\n”, out[0], out[1], out[2], out[3]); return 0; }
Output (verified by compiling and running)
type = 0x42 u16 big-end = 300 u16 little-end= 11265 (same bytes, other convention) u32 big-end = 100000 encoded 100000: 00 01 86 A0

The same code works on a big-endian CPU, on the Cortex-M0 and on a PC, and never forms a misaligned pointer. At -O2 GCC for the Cortex-M4 turns the little-endian version into a single (unaligned-capable) LDR.

Never do this: uint32_t len = *(uint32_t *)&frame[3]; is wrong three times over: the address may be unaligned, strict aliasing is violated, and the byte order is the host’s, not the protocol’s.

6. Packed Structures and Unaligned Members

Protocol headers are sometimes written as __attribute__((packed)) structures, which remove the padding so the layout matches the wire. The structure then contains members that are not naturally aligned.

packed.c
#include <stdio.h> #include <stdint.h> #include <stddef.h> #include <string.h> typedef struct __attribute__((packed)) { uint8_t type; uint16_t length; /* at offset 1: unaligned */ uint32_t stamp; /* at offset 3: unaligned */ } header_t; int main(void) { printf(“sizeof(header_t) = %zu (1 + 2 + 4 data bytes, no padding), alignment = %zu\n”, sizeof(header_t), _Alignof(header_t)); printf(“offsets: type=%zu length=%zu stamp=%zu\n”, offsetof(header_t, type), offsetof(header_t, length), offsetof(header_t, stamp)); uint8_t raw[7] = { 0x07, 0x2C, 0x01, 0x10, 0x00, 0x00, 0x00 }; header_t h; memcpy(&h, raw, sizeof h); /* copy into a properly aligned object */ printf(“type=%u length=%u stamp=%lu (little-endian host layout)\n”, h.type, h.length, (unsigned long)h.stamp); return 0; }
Output (verified by compiling and running)
sizeof(header_t) = 7 (1 + 2 + 4 data bytes, no padding), alignment = 1 offsets: type=0 length=1 stamp=3 type=7 length=300 stamp=16 (little-endian host layout)
packaddr.c
#include <stdint.h> typedef struct __attribute__((packed)) { uint8_t t; uint32_t v; } p_t; uint32_t *get(p_t *p) { return &p->v; /* a uint32_t * that may be unaligned */ }
Taking the address of a packed member
packaddr.c: In function ‘get’: packaddr.c:7:12: warning: taking address of packed member of ‘struct <anonymous>’ may result in an unaligned pointer value [-Waddress-of-packed-member] 7 | return &p->v; /* a uint32_t * that may be unaligned */ | ^~~~~

Accessing a packed member directly (h.stamp) is fine: the compiler knows it is unaligned and generates safe byte or unaligned accesses. Taking its address and passing it as uint32_t * loses that knowledge, which is why GCC warns. A packed struct also fixes only the layout, not the byte order; a big-endian field still needs a swap.

7. Integers, Pointers and the Thumb Bit

Converting between integers and pointers is implementation-defined. The type uintptr_t (from <stdint.h>) is guaranteed to hold a converted pointer and bring it back unchanged; use it whenever you need pointer values as numbers, for example to test alignment or to compare addresses of unrelated objects.

uintptr.c
#include <stdio.h> #include <stdint.h> static int is_aligned(const void *p, size_t alignment) { return ((uintptr_t)p % alignment) == 0; /* alignment must be a power of two */ } int main(void) { uint32_t words[4]; uint8_t *bytes = (uint8_t *)words; /* a byte view of the same storage */ for (int i = 0; i < 4; i++) printf(“bytes + %d : 4-aligned? %s 2-aligned? %s\n”, i, is_aligned(bytes + i, 4) ? “yes” : “no”, is_aligned(bytes + i, 2) ? “yes” : “no”); /* register addresses of the STM32F407 are plain integer constants */ uintptr_t odr = 0x40020C00u + 0x14u; printf(“GPIOD_ODR address 0x%08lX is 4-aligned? %s\n”, (unsigned long)odr, is_aligned((void *)odr, 4) ? “yes” : “no”); return 0; }
Output (verified by compiling and running)
bytes + 0 : 4-aligned? yes 2-aligned? yes bytes + 1 : 4-aligned? no 2-aligned? no bytes + 2 : 4-aligned? no 2-aligned? yes bytes + 3 : 4-aligned? no 2-aligned? no GPIOD_ODR address 0x40020C14 is 4-aligned? yes

For function pointers the Cortex-M4 adds one rule: bit 0 must be 1 (Thumb state), as seen in the vector table (Lesson 8.4). The compiler sets it for function addresses it generates; an address computed by hand must be OR-ed with 1.

CastUseGuarantee
pointer → uintptr_t → same pointerRound tripDefined by the standard
integer constant → pointerRegister addressesImplementation-defined, works on GCC/ARM
pointer → uint32_tPrint or store an address on a 32-bit targetOnly if sizeof(void *) == 4; use uintptr_t to stay portable
function pointer → integerBootloader jumpMind the Thumb bit

8. Best Practices for Pointer Casting and Alignment in Embedded C

  • Cast only when you can state what the data really is; never cast to silence a warning you do not understand.
  • Use uint8_t * for byte views and memcpy to move between byte buffers and typed objects.
  • Parse and build protocol fields with shifts and masks; state the byte order in the function name (rd_u32_be).
  • Align DMA buffers and arrays that are accessed as words: __attribute__((aligned(4))) or alignas(4).
  • Do not take the address of packed members; copy them out.
  • Use uintptr_t, not uint32_t or int, for pointer-to-integer conversions.
  • Keep -Wall -Wextra -Wcast-align -Wstrict-aliasing enabled; treat cast warnings as errors.
  • Test on a big-endian or 64-bit host build to expose hidden assumptions.
  • Never cast away const or volatile.

Key Takeaways — Lesson 9.5

  • A pointer cast changes the type the compiler assumes, not the data.
  • Natural alignment equals the size; the Cortex-M4 tolerates unaligned LDR/STR but faults on LDM/LDRD/VLDR and exclusive accesses.
  • Accessing an object through an unrelated pointer type violates strict aliasing; use memcpy, a union or a byte pointer.
  • The Cortex-M4 is little-endian; network protocols are usually big-endian.
  • Extract multi-byte fields with shifts, which is portable and alignment-safe.
  • Packed structs fix layout only; do not take the address of their members.

Frequently Asked Questions

What does casting a pointer do in C?
It changes the type the compiler uses to interpret the address. The data is not converted, so alignment, byte order and aliasing rules still apply.
What is alignment and why does it matter on the Cortex-M4?
An object of size N is normally placed at an address that is a multiple of N. The Cortex-M4 allows unaligned single-word accesses with LDR/STR but raises a UsageFault for multi-word instructions, exclusive accesses and floating-point loads, and DMA requires aligned addresses.
What is the strict aliasing rule?
It says an object may be accessed only through its own type (or a compatible one, or a character type). Reading a float through a uint32_t pointer is undefined behavior; use memcpy or a union instead.
Is the STM32F407 little-endian or big-endian?
Little-endian: the least significant byte is stored at the lowest address. Network protocols are often big-endian, so multi-byte fields need explicit conversion.
How do I read a 32-bit value from a byte buffer safely?
Assemble it from bytes with shifts, for example (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3] for big-endian, or copy the bytes into a uint32_t with memcpy and then fix the byte order.

Ready to practise?

Next: worked examples with frame decoders, byte swaps, aligned buffers, float bit patterns, packed headers and CRC over a word buffer.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →