🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Free C Programming Course · Structure and Union
Structure Memory Layout in C
See exactly where each structure member lives in RAM, measure offsets with offsetof, and learn why layout matters for drivers and protocols.
What You Will Learn
- What the C standard guarantees about structure member order and addresses
- How to measure member offsets with pointer arithmetic and
offsetof - Why
sizeofis not the sum of member sizes - How to lock a layout in with
_Static_assert
Prerequisites
- Structure definitions and the dot operator
- Pointers and
char *arithmetic basics
Structure Memory Layout in C
Structure memory layout in C answers a practical question: where exactly do the members of a structure live inside RAM? Every embedded engineer needs this answer. Memory-mapped registers, packet buffers, flash records and DMA descriptors are all described as structures, and one wrong assumption about layout means a driver that quietly writes to the wrong byte. This lecture of our free embedded C course shows how to look at the layout yourself instead of guessing.
The Guarantee: Declaration Order and Increasing Addresses
The C standard promises two things about the members of a structure. First, they are placed in memory in the same order you declared them. Second, the address of a later member is always greater than the address of an earlier one. The standard also promises that a pointer to the structure, converted to a pointer to its first member, points to the same location. What it does not promise is that the members are packed tightly. The compiler may insert unused bytes between members. That is the subject of the next lecture.
Seeing the Layout with a Program
Instead of printing raw addresses with %u (which is wrong on 64-bit machines and was only a habit from old 16-bit compilers), we measure the distance of each member from the start of the structure. The program below uses pointer subtraction on char * and also the standard offsetof macro from <stddef.h>, so you can see both methods agree.
#include <stdio.h>
#include <stddef.h>
struct pkt_hdr {
char tag[3];
int seq;
float gain;
};
int main(void)
{
struct pkt_hdr p;
char *base = (char *)&p;
printf("offset of tag = %td\n", (char *)p.tag - base);
printf("offset of seq = %td\n", (char *)&p.seq - base);
printf("offset of gain = %td\n", (char *)&p.gain - base);
printf("offsetof check = %zu %zu %zu\n",
offsetof(struct pkt_hdr, tag),
offsetof(struct pkt_hdr, seq),
offsetof(struct pkt_hdr, gain));
printf("sizeof(p) = %zu\n", sizeof p);
printf("&p == &p.tag ? %s\n", (void *)&p == (void *)p.tag ? "yes" : "no");
return 0;
}
gcc -std=c11 -Wall -Wextra -o b1 b1.c
./b1
Expected output on a typical 64-bit Linux PC (x86-64):
offset of tag = 0
offset of seq = 4
offset of gain = 8
offsetof check = 0 4 8
sizeof(p) = 12
&p == &p.tag ? yes
Read the numbers carefully. The array tag holds 3 bytes, so you might expect seq at offset 3. It is at offset 4. One byte of padding sits between them, because an int prefers to start at an address that is a multiple of 4. The total size is 12, not 3 + 4 + 4 = 11. The exact numbers can differ on other CPUs and compilers, which is why you should always measure rather than assume.
offsetof: The Right Tool
The macro offsetof(type, member) returns the byte distance from the start of a structure type to a member, as a size_t. It needs no variable, works at compile time and is the standard way to verify a layout. Print it with %zu. Embedded teams often put it into a compile-time check so a hardware-facing structure can never change silently:
_Static_assert(offsetof(struct pkt_hdr, seq) == 4, "seq moved");
If a colleague reorders members or switches compiler options, the build breaks immediately with your message instead of the product failing in the field.
Layout of Nested and Array Members
An array member occupies its elements back to back. A member that is itself a structure occupies a block with that inner structure’s own layout, starting at a suitably aligned offset. So the picture of one structure is always a flat run of bytes with a few gaps, no matter how deeply you nest.
| Member kind | Where it sits | Example |
|---|---|---|
| Plain scalar | At the next offset that satisfies its alignment | int seq lands on a multiple of 4 |
| Array of scalars | Elements contiguous, starting aligned for the element type | char tag[3] uses 3 bytes |
| Nested structure | Whole inner block, aligned to the inner structure’s strictest member | A struct point of two ints aligns to 4 |
| Pointer | Aligned to the pointer size | 8 bytes on 64-bit, 4 bytes on Cortex-M |
Real-World Use Cases
- Memory-mapped peripherals. A UART register block is described as a structure whose members line up with hardware offsets. Vendor headers rely on this guarantee, plus careful sizing of each member, so that
UART->DRhits the right address. - Binary file and flash records. Writing a structure to non-volatile storage only works if the reader sees the same layout.
- Debugging. When a debugger shows a corrupted structure, knowing member offsets lets you read raw memory and find which field was overwritten.
Common Mistakes and Troubleshooting
| Mistake | Why it hurts | Fix |
|---|---|---|
Printing addresses with %u | Truncates 64-bit pointers and gives misleading numbers | Use %p with a void * cast, or print offsets with %zu |
| Computing size as the sum of member sizes | Ignores padding, so buffers come out too small | Always use sizeof |
| Writing a structure to a file or socket and reading it on another CPU | Different padding and byte order break the data | Serialise member by member into a defined byte format |
| Casting a byte buffer to a structure pointer | Misaligned access can fault on some cores | Copy bytes into a properly aligned structure with memcpy |
Security note
When a program writes a structure out as raw bytes, the padding bytes may contain leftover stack data from earlier code. Sending those bytes over a network can leak information. Zero the structure first (= {0} or memset) or serialise member by member.
Checking Layout in a Debugger
You do not always have a printing program handy. In GDB you can ask the same questions on the target or on the host. Compile with -g, start the program, and use the following commands:
(gdb) ptype /o struct pkt_hdr
(gdb) print sizeof(struct pkt_hdr)
(gdb) print &p.seq
(gdb) x/12xb &p
ptype /o prints every member with its offset and size and marks the holes, so padding becomes visible at once. x/12xb &p dumps twelve bytes of the object in hexadecimal. Reading raw bytes next to the offsets is the fastest way to find which member overwrote its neighbour.
Layout Checklist for Hardware-Facing Structures
Before you describe a register block, a flash record or a DMA descriptor with a structure, run through this short list:
- Write down the required offset of every field from the datasheet.
- Choose member types whose sizes match the register widths, for example
uint32_tfor a 32-bit register. - Add explicit reserved members for gaps so the offsets match without relying on compiler padding.
- Add one
_Static_assertper important offset and one for the total size. - Mark register structures
volatilewhere the hardware can change them at any time.
Following the list means a compiler upgrade or a change of optimisation level cannot move a register, because the build would fail first.
Layout and Byte Order
Layout tells you where a member is; byte order tells you how its bytes are arranged. A 32-bit integer is stored with its least significant byte first on little-endian CPUs such as x86 and most Cortex-M devices, and with the most significant byte first on big-endian machines. If a structure is copied byte for byte to another system, both the padding and the byte order may differ. That is the reason serious protocols define the wire format byte by byte and convert at the edges.
Key Takeaways
- Members are stored in declaration order at increasing addresses.
- A pointer to a structure points to its first member; no padding precedes it.
- Use
offsetofandsizeof, never hand-added sizes. - Print addresses with
%p, offsets and sizes with%zu. - Verify layouts with static assertions.
Frequently Asked Questions
In what order are structure members stored in memory?
In the order you declared them, at increasing addresses. The compiler may add padding between members, but it never reorders them.
How do I find the offset of a member inside a structure?
Use the offsetof macro from stddef.h, for example offsetof(struct pkt_hdr, seq), and print the result with %zu.
Is the address of a structure the same as the address of its first member?
Yes. A pointer to a structure, suitably converted, points to its first member because no padding is allowed before the first member.
Why should I not print addresses with %u?
An address may be 64 bits wide, so %u prints only part of it. Use %p with a cast to void pointer.
Will my structure have the same layout on every compiler?
No. Padding and alignment rules depend on the CPU and the compiler. Verify with sizeof and offsetof, and add static assertions for layouts that matter.
Can I read structure members through a char pointer?
Yes. Any object may be examined byte by byte through a char pointer, which is how the program in this lecture measures offsets.
Keep Learning C for Embedded Systems
This lecture is part of our free embedded C programming course. Practice every program on your own machine, then move on to the next lecture.

2 Comments