DEV Community

Cover image for How a C Struct Sits in Memory: Size, Padding and Alignment (Linux Kernel Examples)
Vadher Nikunj
Vadher Nikunj

Posted on Originally published at jupiuslearning.com

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

This post was first published on Jupius Learning, where you can read it free with diagrams and practice exercises.

Subscribe to our articles for regular updates.

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;
}
Enter fullscreen mode Exit fullscreen mode

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

gcc student_size.c -o student_size
./student_size
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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:

Type Size in bytes Alignment
char 1 1
short 2 2
int, float 4 4
long, double, any pointer 8 8

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;
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

Output:

item_bad:  24 bytes
item_good: 16 bytes
1000 of item_bad:  24000 bytes
1000 of item_good: 16000 bytes
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 */
};
Enter fullscreen mode Exit fullscreen mode

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.

Read the rest on Jupius

That covers how the compiler pads a struct and how to see the holes. The second half of the post moves into the Linux kernel. It shows how ext2_group_desc names its own padding with bg_pad, why the ext2 superblock ends in 760 bytes of reserved space, how BUILD_BUG_ON stops the kernel build when a struct grows too big, and when the kernel uses __attribute__((packed)) and cache line alignment.

Read the full post on Jupius Learning. It is free, with every example and the diagrams.

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

Top comments (0)