How a C Struct Sits in Memory: Size, Padding and Alignment (Linux Kernel Examples)

Why sizeof on a C struct is bigger than its fields, how padding and alignment work, and how the Linux kernel uses packed, pahole and BUILD_BUG_ON.

Struct padding: struct bad with char a, int b, char c is 12 bytes, and the same fields reordered are 8 bytes

A C struct is often bigger than the sum of its fields. The compiler puts each field at an address that suits its type, and to do that it sometimes leaves empty bytes between fields, or at the end. Those empty bytes are called padding. The rule that decides where a field may start is called alignment.

In the first post of this series we declared a struct student, filled it and read it. In the last post we gave it a short name with typedef. This time we look at how that struct is laid out in memory, and how the Linux kernel controls the layout of its own structs.

All the sizes in this post come from gcc on a 64-bit x86 Linux machine. I compiled and ran every program shown here. On a different CPU or compiler a few numbers may change, and I will point out where.

Why is sizeof a struct bigger than its fields?

Here is the student struct again. This time we print its size and where each field starts.

#include <stdio.h>
#include <stddef.h>

struct student {
    int   roll_no;
    char  name[50];
    float marks;
};

int main(void)
{
    printf("sizeof(int)   = %zu\n", sizeof(int));
    printf("sizeof(float) = %zu\n", sizeof(float));
    printf("sizeof(struct student) = %zu\n", sizeof(struct student));

    printf("roll_no at offset %zu\n", offsetof(struct student, roll_no));
    printf("name    at offset %zu\n", offsetof(struct student, name));
    printf("marks   at offset %zu\n", offsetof(struct student, marks));

    return 0;
}

Save it as student_size.c, then compile and run it:

gcc student_size.c -o student_size
./student_size

In PowerShell with MinGW, run it with .\student_size.exe.

Output:

sizeof(int)   = 4
sizeof(float) = 4
sizeof(struct student) = 60
roll_no at offset 0
name    at offset 4
marks   at offset 56

The fields add up to 4 + 50 + 4 = 58 bytes. sizeof says 60.

roll_no starts at byte 0 and takes 4 bytes. name starts at byte 4 and takes 50 bytes, so it ends at byte 53. The next free byte is 54, but marks starts at 56. Bytes 54 and 55 are padding. Nobody uses them. They are there so that marks starts at a multiple of 4.

offsetof is a macro from <stddef.h>. It tells you how many bytes from the start of the struct a field begins. It is the simplest way to see padding for yourself.

What is alignment in C?

Most types have an alignment. It is the number that the field's address must be a multiple of. On x86-64 Linux with gcc, the common ones look like this:

TypeSize in bytesAlignment
char11
short22
int, float44
long, double, any pointer88

A char can go anywhere. An int must start at an address that is a multiple of 4. A pointer must start at a multiple of 8.

The reason is the hardware. A CPU reads memory in chunks, and a value that sits neatly inside one chunk is quick to load. On x86 a misaligned read still works, it is just slower in some cases. On some other CPUs a misaligned read can trap. So C compilers follow the alignment rules of the platform, and they add padding to make the rules hold.

The compiler follows two simple rules for a struct:

  • Each field starts at the next offset that is a multiple of its own alignment.
  • The whole struct gets the alignment of its strictest field, and its size is rounded up to a multiple of that.

The second rule is why padding can appear at the end. If you make an array of structs, every element must start at a properly aligned address too, not only the first one.

Our student struct has int and float fields, so its alignment is 4. 58 is not a multiple of 4, so the struct is 60 bytes. In this case the padding happens to sit before marks, and no extra bytes are needed at the end.

How field order changes the size of a C struct

Here are two structs with the same three fields in a different order.

#include <stdio.h>
#include <stddef.h>

struct bad {
    char a;
    int  b;
    char c;
};

struct good {
    int  b;
    char a;
    char c;
};

int main(void)
{
    struct bad  x = { 0 };
    struct good y = { 0 };

    printf("struct bad:  size %zu, a at %zu, b at %zu, c at %zu\n",
           sizeof x, offsetof(struct bad, a),
           offsetof(struct bad, b), offsetof(struct bad, c));
    printf("struct good: size %zu, b at %zu, a at %zu, c at %zu\n",
           sizeof y, offsetof(struct good, b),
           offsetof(struct good, a), offsetof(struct good, c));
    return 0;
}

Output:

struct bad:  size 12, a at 0, b at 4, c at 8
struct good: size 8, b at 0, a at 4, c at 5

Byte layout of struct bad (char a, 3 byte hole, int b, char c, 3 bytes end padding, 12 bytes) and struct good (int b, char a, char c, 2 bytes end padding, 8 bytes)

In struct bad, a takes byte 0. b is an int, so it can't start at 1. It goes to 4, and bytes 1 to 3 are a hole. c sits at byte 8. The struct needs a size that is a multiple of 4, so bytes 9 to 11 are padding at the end. That is 6 bytes of data in a 12 byte struct.

In struct good, b goes first at byte 0. The two char fields fit right after it at 4 and 5. Two bytes of padding at the end round the size up to 8.

Nothing about the data changed. Only the order did, and the struct shrank by a third.

The gap grows when pointers are involved, because a pointer needs 8 byte alignment on a 64-bit machine:

#include <stdio.h>

struct item_bad {
    char  flag;
    void *data;
    char  kind;
};

struct item_good {
    void *data;
    char  flag;
    char  kind;
};

int main(void)
{
    printf("item_bad:  %zu bytes\n", sizeof(struct item_bad));
    printf("item_good: %zu bytes\n", sizeof(struct item_good));
    printf("1000 of item_bad:  %zu bytes\n", 1000 * sizeof(struct item_bad));
    printf("1000 of item_good: %zu bytes\n", 1000 * sizeof(struct item_good));
    return 0;
}

Output:

item_bad:  24 bytes
item_good: 16 bytes
1000 of item_bad:  24000 bytes
1000 of item_good: 16000 bytes

For one struct, 8 bytes does not matter. For a thousand of them it is 8000 bytes. The Linux kernel keeps millions of some structs in memory at once, one for every page of RAM or every open file. That is why kernel developers care about the order of fields.

A simple habit works most of the time: put the biggest fields first, pointers and long values, then int, then short, then char. Related fields often still belong together for readability, so it is a habit, not a law.

See the holes with pahole

Counting offsets by hand gets tiring. The pahole tool reads the debug information in a compiled program and prints every struct with its holes marked. It comes in the dwarves package on Debian and Ubuntu (sudo apt install dwarves).

Compile the order example with -g so the debug information is there, then ask pahole about struct bad:

gcc -g order.c -o order
pahole -C bad order

Output:

struct bad {
	char                       a;                    /*     0     1 */

	/* XXX 3 bytes hole, try to pack */

	int                        b;                    /*     4     4 */
	char                       c;                    /*     8     1 */

	/* size: 12, cachelines: 1, members: 3 */
	/* sum members: 6, holes: 1, sum holes: 3 */
	/* padding: 3 */
	/* last cacheline: 12 bytes */
};

The two numbers on each line are the offset and the size. pahole finds the 3 byte hole after a and the 3 bytes of padding at the end, and it even suggests you try to pack the struct. On my machine pahole also printed a short warning line about a missing BTF section. You can ignore that for a normal user program.

The same tool works on the Linux kernel itself. If you have a vmlinux with debug information, pahole -C task_struct vmlinux prints the full layout of the process descriptor. We walked through its fields in task_struct in the Linux Kernel: Every Field Explained. Kernel developers use pahole in exactly this way to find holes in busy structs and move fields around to close them.

Padding you can see: ext2_group_desc in the Linux kernel

So far the compiler has added padding by itself. Structs that describe data on a disk are different. The layout on disk is fixed, so the kernel spells out every byte, padding included.

The ext2 filesystem splits a disk into block groups. Each group is described by a small struct. This is how the Linux kernel defines it in fs/ext2/ext2.h:

/* From the Linux kernel, fs/ext2/ext2.h */
struct ext2_group_desc
{
	__le32	bg_block_bitmap;		/* Blocks bitmap block */
	__le32	bg_inode_bitmap;		/* Inodes bitmap block */
	__le32	bg_inode_table;		/* Inodes table block */
	__le16	bg_free_blocks_count;	/* Free blocks count */
	__le16	bg_free_inodes_count;	/* Free inodes count */
	__le16	bg_used_dirs_count;	/* Directories count */
	__le16	bg_pad;
	__le32	bg_reserved[3];
};

__le32 and __le16 are kernel types for 32-bit and 16-bit numbers stored in little-endian byte order. For size and alignment they act like uint32_t and uint16_t, so we can copy the struct into a normal program:

#include <stdio.h>
#include <stddef.h>
#include <stdint.h>

/* Same layout as struct ext2_group_desc in the Linux kernel.
   The kernel uses __le32 and __le16; uint32_t and uint16_t
   have the same size. */
struct ext2_group_desc {
    uint32_t bg_block_bitmap;
    uint32_t bg_inode_bitmap;
    uint32_t bg_inode_table;
    uint16_t bg_free_blocks_count;
    uint16_t bg_free_inodes_count;
    uint16_t bg_used_dirs_count;
    uint16_t bg_pad;
    uint32_t bg_reserved[3];
};

_Static_assert(sizeof(struct ext2_group_desc) == 32,
               "ext2_group_desc must be 32 bytes on disk");

int main(void)
{
    printf("sizeof = %zu\n", sizeof(struct ext2_group_desc));
    printf("bg_used_dirs_count at %zu\n",
           offsetof(struct ext2_group_desc, bg_used_dirs_count));
    printf("bg_pad             at %zu\n",
           offsetof(struct ext2_group_desc, bg_pad));
    printf("bg_reserved        at %zu\n",
           offsetof(struct ext2_group_desc, bg_reserved));
    return 0;
}

Output:

sizeof = 32
bg_used_dirs_count at 16
bg_pad             at 18
bg_reserved        at 20

Three 4 byte fields take bytes 0 to 11. Three 2 byte fields take bytes 12 to 17. That leaves bg_reserved wanting to start at a multiple of 4, and the next free byte is 18. bg_pad fills bytes 18 and 19 by name.

Here is the interesting part. I tried deleting the bg_pad line, and the struct was still 32 bytes. The compiler simply added the same 2 bytes of padding on its own. So why write bg_pad at all?

Because a hidden hole is easy to forget. With a named field, anyone reading the struct can see that bytes 18 and 19 exist, and the code that creates a filesystem can set them to zero on purpose. The on-disk format stays the same no matter which compiler built the kernel or the tools.

The bg_reserved array is also padding of a kind. It keeps the struct at 32 bytes and leaves room for future fields, so newer versions of the format can use those bytes without moving anything.

The ext2 superblock does the same thing on a larger scale. struct ext2_super_block in the same header has a few dozen fields, and its last field is:

	__u32	s_reserved[190];	/* Padding to the end of the block */

I copied the whole struct into a test program. The real fields end at offset 264, and 190 more 4 byte values take 760 bytes, so the struct is exactly 1024 bytes. That is the size the superblock takes on disk. The comment in the kernel source says it plainly: padding to the end of the block.

Checking a struct size at compile time with BUILD_BUG_ON

If a struct has to be a certain size, it is better to have the compiler check it than to find out when a disk image will not mount.

You may have noticed the _Static_assert line in the program above. It is standard C since C11. If the condition is false, compilation stops with your message. To see it fail, change bg_pad to a uint32_t by mistake:

    uint16_t bg_used_dirs_count;
    uint32_t bg_pad;              /* should have been uint16_t */
    uint32_t bg_reserved[3];

gcc refuses to build it:

assert_fail.c:14:1: error: static assertion failed: "ext2_group_desc must be 32 bytes on disk"
   14 | _Static_assert(sizeof(struct ext2_group_desc) == 32,
      | ^~~~~~~~~~~~~~

The struct grew to 36 bytes, and the check caught it before the program ever ran.

The Linux kernel has its own macro for this, BUILD_BUG_ON(condition). It breaks the build when the condition is true. Here is a real use from the TCP code, in tcp_init() in net/ipv4/tcp.c:

/* From the Linux kernel, net/ipv4/tcp.c */
BUILD_BUG_ON(sizeof(struct tcp_skb_cb) >
	     sizeof_field(struct sk_buff, cb));

Every network packet in the kernel is described by a struct sk_buff. It has a small scratch area called cb, 48 bytes, that each protocol layer can use for its own notes. TCP keeps its notes in struct tcp_skb_cb and stores them in that area. If someone adds a field and tcp_skb_cb no longer fits, the kernel will not compile. That is much better than TCP silently writing past the end of cb at run time. sizeof_field is a kernel helper that gives the size of one field of a struct.

attribute((packed)) for network headers

Sometimes you want no padding at all. A network packet or a file header arrives as a run of bytes in a fixed format, and you want to lay a struct over those bytes and read the fields. If the compiler adds padding, the fields of your struct will not line up with the bytes.

gcc has an attribute for this. __attribute__((packed)) tells the compiler not to add any padding inside the struct and to give it an alignment of 1.

#include <stdio.h>
#include <stddef.h>
#include <stdint.h>

struct msg_hdr {
    uint8_t  type;
    uint32_t length;
    uint16_t id;
};

struct msg_hdr_packed {
    uint8_t  type;
    uint32_t length;
    uint16_t id;
} __attribute__((packed));

int main(void)
{
    printf("normal: size %zu, length at %zu, id at %zu\n",
           sizeof(struct msg_hdr),
           offsetof(struct msg_hdr, length),
           offsetof(struct msg_hdr, id));
    printf("packed: size %zu, length at %zu, id at %zu\n",
           sizeof(struct msg_hdr_packed),
           offsetof(struct msg_hdr_packed, length),
           offsetof(struct msg_hdr_packed, id));
    return 0;
}

Output:

normal: size 12, length at 4, id at 8
packed: size 7, length at 1, id at 5

The packed version is exactly the 7 bytes a protocol on the wire would send: one byte of type, four bytes of length, two bytes of id, one right after the other.

The Linux kernel marks its Ethernet header this way. This is from include/uapi/linux/if_ether.h:

/* From the Linux kernel, include/uapi/linux/if_ether.h */
struct ethhdr {
	unsigned char	h_dest[ETH_ALEN];	/* destination eth addr	*/
	unsigned char	h_source[ETH_ALEN];	/* source ether addr	*/
	__be16		h_proto;		/* packet type ID field	*/
} __attribute__((packed));

ETH_ALEN is 6, the length of a MAC address. __be16 is a 16-bit number in big-endian order, which is the byte order used on the network. With gcc on x86-64, this struct is 14 bytes whether it is packed or not, because the fields happen to line up. I checked both. The kernel packs it anyway, so the struct is 14 bytes with an alignment of 1 on every CPU and compiler it supports. An Ethernet header can then be read straight out of a packet buffer at any address.

Packed is not free. A field like length above sits at offset 1, which is not a multiple of 4. On x86 that read is a little slower. On some other CPUs the compiler has to read it a byte at a time. Taking a pointer to a packed field and passing it around can also cause trouble, and gcc will warn about it. So the kernel uses packed for formats that come from outside, like disk and network data, and leaves its ordinary in-memory structs alone.

____cacheline_aligned: padding on purpose

The last case goes the other way. Sometimes the kernel adds more padding than the compiler would, to make a struct start on its own cache line.

A CPU does not move single bytes between memory and its cache. It moves a cache line at a time, which is 64 bytes on most x86 machines. If two CPUs keep writing to two different variables that happen to sit in the same cache line, the line has to bounce between them on every write. The program is correct, but slow. This is called false sharing.

The fix is to give each busy piece of data its own cache line. gcc lets you raise the alignment of a struct with __attribute__((aligned(N))):

#include <stdio.h>

struct counter {
    long hits;
};

struct counter_aligned {
    long hits;
} __attribute__((aligned(64)));

int main(void)
{
    struct counter         plain[2];
    struct counter_aligned spaced[2];

    printf("counter:         size %zu, gap between [0] and [1] = %td\n",
           sizeof(struct counter),
           (char *)&plain[1] - (char *)&plain[0]);
    printf("counter_aligned: size %zu, gap between [0] and [1] = %td\n",
           sizeof(struct counter_aligned),
           (char *)&spaced[1] - (char *)&spaced[0]);
    return 0;
}

Output:

counter:         size 8, gap between [0] and [1] = 8
counter_aligned: size 64, gap between [0] and [1] = 64

The aligned struct holds the same 8 bytes of data, but its size is now 64. Each element of the array starts on a new cache line, so two CPUs updating spaced[0] and spaced[1] will not get in each other's way.

The Linux kernel wraps this in macros from include/linux/cache.h. ____cacheline_aligned aligns to the cache line size of the machine. ____cacheline_aligned_in_smp does the same, but only on kernels built for more than one CPU, since a single CPU has nothing to share with. Here is how struct per_cpu_pages ends in include/linux/mmzone.h. It is the small cache of free pages the kernel keeps for each CPU:

/* Simplified from the Linux kernel, include/linux/mmzone.h */
struct per_cpu_pages {
	spinlock_t lock;	/* Protects lists field */
	int count;		/* number of pages in the list */
	int high;		/* high watermark, emptying needed */
	int batch;		/* chunk size for buddy add/remove */
	/* ... more fields ... */
} ____cacheline_aligned_in_smp;

The same file uses a related macro, CACHELINE_PADDING, inside struct zone. It drops an empty padding member between groups of fields, so that fields written often by the page allocator do not share a cache line with fields that are mostly read. It is the same idea as bg_pad: padding with a name, put there on purpose.

A quick way to think about struct layout

The first question I ask about a struct is where its bytes come from. If the struct only ever lives in memory, I let the compiler pad it and order the fields from biggest to smallest so the holes stay small. If the bytes come from a disk or a network, I want every byte spelled out, with named padding or packed, and a compile-time check on the size. Cache line alignment is a separate question that only comes up when several CPUs write to the same data.

The Linux kernel does all of this, often in the same header file. Once you know what padding is, odd-looking fields like bg_pad and s_reserved start to make sense.

What comes next

We now know why sizeof can surprise you, how to see the holes with offsetof and pahole, and how the Linux kernel takes control of struct layout with explicit padding, packed, BUILD_BUG_ON and cache line alignment.

In the next post, Structs Inside Structs, we will put one struct inside another as a field, and see how the Linux kernel builds bigger structs out of smaller ones. The padding rules from this post still apply there, one level down.

If you want to practice this with small exercises that check your code as you go, the C programming course at Jupius Learning covers structs and memory step by step.

Frequently asked questions

Why is sizeof a struct larger than the sum of its members?

Because the compiler adds padding. Each field has to start at an offset that is a multiple of its alignment, so the compiler may leave unused bytes between fields. It may also add bytes at the end so the size is a multiple of the struct's alignment. Our struct student has 58 bytes of fields and a size of 60.

How do I find the offset of a field in a C struct?

Use the offsetof macro from <stddef.h>, for example offsetof(struct student, marks). It returns the number of bytes from the start of the struct to that field. For a full picture of every field and hole, compile with -g and run pahole -C struct_name program.

Does the order of fields change the size of a struct?

Yes. The same fields in a different order can give a different size. char, int, char is 12 bytes with gcc on x86-64, and int, char, char is 8 bytes. Putting larger fields first usually leaves fewer holes.

What does attribute((packed)) do?

It tells gcc not to add padding inside the struct and to give it an alignment of 1. The struct then matches a fixed byte format exactly. The Linux kernel uses it for structs like ethhdr that describe network or disk data. Reading misaligned fields can be slower, so it is not a good default for ordinary structs.

What is BUILD_BUG_ON in the Linux kernel?

It is a macro that stops the kernel build when a condition is true at compile time. The kernel uses it to check struct sizes, for example to make sure struct tcp_skb_cb still fits inside the cb area of struct sk_buff. In your own C code, _Static_assert does the same job.

Continue with a course

Article notes

Email when a new article is published. A confirm link comes first.

Topics