C Pointers to Structs and the Arrow Operator: Linux Kernel

Learn what a pointer to a struct is in C, what the arrow operator does, and how the Linux kernel uses current, parent pointers and shared structs.

Pointers to structs: pointer p holds the address of a struct student, with p->id reaching id, next to the Linux kernel current pointer leading to a task_struct and its real_parent

In the last post I wrote things like s->ops->area(s) and file->f_op->read without stopping to explain them. That is where this post starts. We look at a pointer to a struct on its own, what the arrow operator does, and why the Linux kernel passes and links its structs by pointer almost everywhere.

If you have read the first post in this series, you know the dot operator. You use it when you have the struct itself. This post is about the other case, when all you have is the address of the struct.

All the output in this post comes from gcc 14 on a 64-bit x86 Linux machine. The kernel snippets are copied from recent mainline source and trimmed.

What is a pointer to a struct in C?

A pointer to a struct is a variable that holds the address of a struct. You declare it with a *, the same as any other pointer, and you fill it with &.

#include <stdio.h>

struct student {
    int id;
    char grade;
    double score;
};

int main(void)
{
    struct student s = { 42, 'A', 91.5 };
    struct student *p = &s;

    printf("s.id     = %d\n", s.id);
    printf("(*p).id  = %d\n", (*p).id);
    printf("p->id    = %d\n", p->id);

    p->score = 95.0;
    printf("s.score after p->score = 95.0: %.1f\n", s.score);

    printf("sizeof(s)  = %zu\n", sizeof(s));
    printf("sizeof(*p) = %zu\n", sizeof(*p));
    printf("sizeof(p)  = %zu\n", sizeof(p));
    printf("p == &s: %s\n", p == &s ? "yes" : "no");
    return 0;
}

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

gcc ptr_basic.c -o ptr_basic
./ptr_basic

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

Output:

s.id     = 42
(*p).id  = 42
p->id    = 42
s.score after p->score = 95.0: 95.0
sizeof(s)  = 16
sizeof(*p) = 16
sizeof(p)  = 8
p == &s: yes

p points at s. It is not a copy. When we write p->score = 95.0, the score inside s changes, and the next line proves it.

Look at the sizes. sizeof(s) and sizeof(*p) are both 16, because *p is the struct that p points at. The pointer itself, sizeof(p), is 8 bytes on a 64-bit machine. It does not matter how big the struct is. The pointer stays 8 bytes. Why the struct is 16 and not 13 is the story of the padding post.

What does the arrow operator do?

The arrow operator -> is a short way to write "go to the struct this pointer points at, then take this field". These two lines mean exactly the same thing:

(*p).id
p->id

*p follows the pointer and gives you the struct. Then .id picks the field. The brackets are needed, and that is the reason -> exists.

The dot binds tighter than the star. So *p.id is read as *(p.id). That asks for the field id of p, and then tries to follow it as a pointer. But p is a pointer, not a struct, so it has no fields. Here is what gcc says:

printf("%d\n", *p.id);
bad_dot.c: In function 'main':
bad_dot.c:13:22: error: 'p' is a pointer; did you mean to use '->'?
   13 |     printf("%d\n", *p.id);
      |                      ^
      |                      ->

The compiler even suggests the fix. The rule is easy to remember:

  • Use . when you have a struct variable.
  • Use -> when you have a pointer to a struct.

Both can show up in one expression. If a struct holds another struct inside it, as in the nesting post, you use an arrow for the pointer and then a dot for the inner struct, like p->addr.pin. We will see the kernel do exactly that later.

Why pass a struct by pointer, in C and in the Linux kernel?

When you pass a struct to a function by value, C copies the whole struct. The function works on its own copy. Whatever it changes is lost when it returns.

#include <stdio.h>

struct stats {
    int count;
    int samples[16];
};

static void add_copy(struct stats s, int v)
{
    s.samples[s.count] = v;
    s.count++;
}

static void add_ptr(struct stats *s, int v)
{
    s->samples[s->count] = v;
    s->count++;
}

static int total(const struct stats *s)
{
    int i, sum = 0;

    for (i = 0; i < s->count; i++)
        sum += s->samples[i];
    return sum;
}

int main(void)
{
    struct stats st = { 0 };

    add_copy(st, 10);
    printf("after add_copy: count = %d\n", st.count);

    add_ptr(&st, 10);
    add_ptr(&st, 25);
    printf("after add_ptr:  count = %d, total = %d\n", st.count, total(&st));

    printf("sizeof(struct stats)   = %zu\n", sizeof(struct stats));
    printf("sizeof(struct stats *) = %zu\n", sizeof(struct stats *));
    return 0;
}

Output:

after add_copy: count = 0
after add_ptr:  count = 2, total = 35
sizeof(struct stats)   = 68
sizeof(struct stats *) = 8

add_copy did its work on a copy, so st.count is still 0. add_ptr got the address of st, so it changed the real thing.

There is a second reason, and it is size. Calling add_copy copies 68 bytes on every call. Calling add_ptr passes 8. For a small struct the difference is tiny. For a struct with hundreds of fields it is not.

The total function takes a const struct stats *. The const is a promise that the function will only read through the pointer. If it tries to write, the compiler stops it:

const_bad.c: In function 'reset':
const_bad.c:7:14: error: assignment of member 'count' in read-only object
    7 |     s->count = 0;
      |              ^

You will see const struct in a lot of kernel function signatures for this reason. It tells the reader that the function only looks at the struct.

Pointers to structs on the heap and in arrays

A pointer can also point at memory you ask for at run time. For a struct, the usual way to write the size is sizeof *p. That way the line stays right even if you later change the type of p.

Pointers also work with arrays of structs. Adding 1 to a struct pointer moves it forward by one whole struct, not by one byte.

#include <stdio.h>
#include <stdlib.h>

struct item {
    int id;
    int qty;
};

int main(void)
{
    struct item *p = malloc(sizeof *p);

    if (p == NULL)
        return 1;

    p->id = 7;
    p->qty = 3;
    printf("heap item: id = %d, qty = %d\n", p->id, p->qty);
    free(p);

    struct item shelf[3] = { { 1, 10 }, { 2, 20 }, { 3, 30 } };
    struct item *q = shelf;

    printf("q->qty       = %d\n", q->qty);
    printf("(q + 1)->qty = %d\n", (q + 1)->qty);
    printf("q[2].qty     = %d\n", q[2].qty);
    printf("step between items = %td bytes\n",
           (char *)(q + 1) - (char *)q);

    q++;
    printf("after q++, q->id = %d\n", q->id);
    return 0;
}

Output:

heap item: id = 7, qty = 3
q->qty       = 10
(q + 1)->qty = 20
q[2].qty     = 30
step between items = 8 bytes
after q++, q->id = 2

struct item is 8 bytes, so q + 1 is 8 bytes after q. The compiler does that multiplication for you. Notice q[2].qty too. The square brackets already follow a pointer, so you use a dot after them, not an arrow.

Check the result of malloc before you use it, as the code does. If it returns NULL and you write p->id, you are using a pointer that points at nothing. We come back to that near the end.

How the Linux kernel finds the running process with current

Now the kernel. Every piece of kernel code that runs on behalf of a process can use a name called current. It is a pointer to the struct task_struct of the process that is running on this CPU right now. If you have not met that struct yet, the task_struct post goes through its fields.

On x86 it looks like this:

/* From the Linux kernel, arch/x86/include/asm/current.h (trimmed) */
struct task_struct;

static __always_inline struct task_struct *get_current(void)
{
	if (IS_ENABLED(CONFIG_USE_X86_SEG_SUPPORT))
		return this_cpu_read_const(const_current_task);

	return this_cpu_read_stable(current_task);
}

#define current get_current()

Each CPU keeps its own pointer to the task it is running. current just reads it. You can ignore the per-CPU details for now. The point is that current has the type struct task_struct *. So every use of it needs the arrow.

Here is the real code behind two system calls you know from user space, from kernel/sys.c:

/* From the Linux kernel, kernel/sys.c */
SYSCALL_DEFINE0(getpid)
{
	return task_tgid_vnr(current);
}

SYSCALL_DEFINE0(getppid)
{
	int pid;

	rcu_read_lock();
	pid = task_tgid_vnr(rcu_dereference(current->real_parent));
	rcu_read_unlock();

	return pid;
}

getpid hands the current pointer to a helper. getppid follows the arrow from current to its real_parent field and asks for the process ID of whatever that is. The rcu_ lines make that read safe while other code may be changing the parent. Do not worry about them yet. The part we care about is current->real_parent.

Notice that the parent is also a struct task_struct *. A task points at another task. That is the next idea.

Linking Linux kernel structs by pointer: parent and real_parent

Here are the fields of task_struct that hold the family tree, trimmed from include/linux/sched.h:

/* From the Linux kernel, include/linux/sched.h, in struct task_struct (trimmed) */
	pid_t				pid;
	pid_t				tgid;

	/* Real parent process: */
	struct task_struct __rcu	*real_parent;

	/* Recipient of SIGCHLD, wait4() reports: */
	struct task_struct __rcu	*parent;

	/*
	 * Children/sibling form the list of natural children:
	 */
	struct list_head		children;
	struct list_head		sibling;
	struct task_struct		*group_leader;

Look at the types. real_parent and parent are pointers to a task_struct. So is group_leader. None of them is a task_struct stored inside a task_struct. C does not allow that. A struct cannot contain itself, because it would have to be infinitely big. Here is what gcc says if you try:

struct proc {
    int pid;
    struct proc parent;
};
self_embed.c:3:17: error: field 'parent' has incomplete type
    3 |     struct proc parent;
      |                 ^~~~~~

A pointer to the same struct is fine, because a pointer has a fixed size no matter what it points at. That is how a struct can refer to another one of its own kind.

The children and sibling fields are list_head structs, which are embedded, not pointed at. That is the container_of trick from the nesting post. So task_struct uses both styles side by side. A pointer says "this one is somewhere else, go and find it". An embedded struct says "this is part of me".

Here is the same idea as a small user-space program. The names copy the kernel, but this is not kernel code.

#include <stdio.h>

struct proc {
    int pid;
    const char *name;
    struct proc *parent;
};

static void show_chain(const struct proc *p)
{
    for (; p != NULL; p = p->parent)
        printf("%d %s\n", p->pid, p->name);
}

int main(void)
{
    struct proc init  = { 1,    "init",  NULL };
    struct proc shell = { 812,  "bash",  &init };
    struct proc edit  = { 2040, "vim",   &shell };

    show_chain(&edit);

    printf("edit.parent->name = %s\n", edit.parent->name);
    printf("edit.parent->parent->name = %s\n", edit.parent->parent->name);
    printf("sizeof(struct proc) = %zu\n", sizeof(struct proc));
    return 0;
}

Output:

2040 vim
812 bash
1 init
edit.parent->name = bash
edit.parent->parent->name = init
sizeof(struct proc) = 24

The loop in show_chain is the whole trick. p = p->parent moves the pointer one step up the tree. When it reaches init, whose parent is NULL, the loop ends. A NULL pointer is how C says "there is nothing more here".

The two printf lines at the end chain arrows. edit.parent->parent->name reads left to right. Start with edit, take its parent pointer, follow it, take that struct's parent pointer, follow it, and read the name. Each arrow is one hop.

The numbers here are made up for the demo. In a real system the top of the tree is usually the process with ID 1, and the other processes lead back to it through their parents.

Why Linux kernel tasks share structs through pointers

The same choice, embed or point, shows up for a different reason in task_struct. Look at a few more fields:

/* From the Linux kernel, include/linux/sched.h, in struct task_struct (trimmed) */
	struct mm_struct		*mm;
	struct mm_struct		*active_mm;
	/* ... */
	const struct cred		*cred;
	/* ... */
	/* Filesystem information: */
	struct fs_struct		*fs;

	/* Open file information: */
	struct files_struct		*files;

mm describes the memory of a process, its address space. files holds the table of open files. Both are pointers, not embedded structs, and that is on purpose.

A process can have many threads, and each thread has its own task_struct. The threads of one process share one address space. If the memory description were stored inside each task_struct, every thread would have its own copy, and a change made by one thread would never reach the others. With a pointer, the threads simply point at the same mm_struct. There is one real copy.

Here is a tiny model of that:

#include <stdio.h>

struct mm {
    int users;
    long pages;
};

struct task {
    int pid;
    struct mm *mm;
};

int main(void)
{
    struct mm space = { 1, 100 };
    struct task main_thread = { 500, &space };
    struct task worker = { 501, main_thread.mm };

    worker.mm->users++;
    worker.mm->pages += 25;

    printf("main_thread sees pages = %ld, users = %d\n",
           main_thread.mm->pages, main_thread.mm->users);
    printf("same mm: %s\n", main_thread.mm == worker.mm ? "yes" : "no");
    return 0;
}

Output:

main_thread sees pages = 125, users = 2
same mm: yes

The worker changed pages through its own pointer, and the main thread saw it, because both pointers lead to space. The users field is a counter of how many tasks use this mm. The kernel keeps counters like that so it knows when the last user is gone and the struct can be freed. This is only a model. The real mm_struct is far bigger.

So there is a simple way to think about the choice:

  • Embed a struct when the inner part belongs to this one object alone.
  • Use a pointer when the inner part is shared, can be somewhere else, or can be missing.

A pointer can be NULL. An embedded struct is always there. Kernel threads, for example, have no user address space of their own, and for them the mm pointer is NULL.

Chained arrows in the Linux kernel: file, dentry and inode

Long chains of arrows are normal in kernel code. Here are two real ones. The first is from include/linux/fs.h:

/* From the Linux kernel, include/linux/fs.h, in dir_emit_dot() */
	return ctx->actor(ctx, ".", 1, ctx->pos,
			  file->f_path.dentry->d_inode->i_ino, DT_DIR);

Read file->f_path.dentry->d_inode->i_ino one piece at a time. file is a struct file *, so we use an arrow to reach f_path. Inside struct file, the field f_path is a struct path that is stored inline, so the next step is a dot. A struct path holds two pointers, mnt and dentry. So dentry is followed by an arrow to reach d_inode. That is a pointer to the struct inode, and one more arrow reaches i_ino, the inode number.

That one expression mixes arrow, dot, arrow, arrow. It is the rule from the start of the post, used four times in a row. A pointer gets an arrow. A struct stored inside gets a dot.

The second one is from kernel/sys.c, inside the umask system call:

/* From the Linux kernel, kernel/sys.c, in SYSCALL_DEFINE1(umask, ...) */
	mask = xchg(&current->fs->umask, mask & S_IRWXUGO);

Here current->fs follows the pointer to the process's fs_struct, and ->umask reaches the field inside it. The & in front takes the address of that field, so xchg can swap the value in place. The & applies to the whole expression current->fs->umask, because -> binds tighter than &.

A small Linux kernel module that reads current

Here is a short module that uses current the way kernel code does. It prints the name and ID of the process that loads it, and the name and ID of that process's parent.

// SPDX-License-Identifier: GPL-2.0
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/rcupdate.h>

static int __init who_init(void)
{
	struct task_struct *me = current;
	struct task_struct *parent;

	rcu_read_lock();
	parent = rcu_dereference(me->real_parent);
	pr_info("who: I am %s (pid %d), my parent is %s (pid %d)\n",
		me->comm, me->pid, parent->comm, parent->pid);
	rcu_read_unlock();
	return 0;
}

static void __exit who_exit(void)
{
	pr_info("who: bye\n");
}

module_init(who_init);
module_exit(who_exit);
MODULE_LICENSE("GPL");

This is a kernel module, not a user-space program, so you cannot run it with gcc alone. It builds cleanly against the 6.12 kernel headers, but it has not been loaded or run for this post, so I am not showing any log output for it. If you try it, use a virtual machine, not the computer you work on.

The code is the same pattern as everything above. me is a copy of the current pointer, not a copy of the struct. me->real_parent is another pointer. comm is the short name of the program, and pid is its ID. The module prints one line to the kernel log when it loads and one when it is removed.

What goes wrong with struct pointers in C and the Linux kernel?

Most bugs with struct pointers come down to one problem. The pointer does not point at a valid struct when you use the arrow.

The most common case is NULL. Here is a small linked struct with a next field that was never set:

#include <stdio.h>

struct node {
    int value;
    struct node *next;
};

int main(void)
{
    struct node a = { 5, NULL };

    printf("a.value = %d\n", a.value);
    printf("a.next is %s\n", a.next == NULL ? "NULL" : "set");
    printf("%d\n", a.next->value);
    printf("never printed\n");
    return 0;
}

Run in a terminal, the output is:

a.value = 5
a.next is NULL
Segmentation fault

a.next->value tries to read a field at address 0 plus a small offset. The operating system does not allow that, so it stops the program. In the Linux kernel the same mistake is an oops, a crash report in the kernel log. Depending on where it happens, it can take the whole machine down.

So the safe habit is the same as with function pointers in the last post. If a pointer can be NULL, check it before the arrow. In the family tree loop above, the check was the p != NULL in the for line.

There are two other cases to watch for:

  • A pointer that was never set. A local struct node *p; holds garbage until you assign something to it. Set it to NULL or to a real address when you declare it.
  • A pointer to something that is gone. If a function returns &local, the local struct is freed when the function returns, and the pointer now leads to memory that may be reused. The kernel has a lot of care and counters, like users in our model, to avoid exactly this.

Practice exercises

Try these with gcc on your own machine. In PowerShell with MinGW, run the program with .\name.exe.

  1. In ptr_basic.c, add a second pointer struct student *q = p; and change the grade through q. Print s.grade and explain why it changed.

  2. In by_value.c, write a function reset_stats(struct stats *s) that sets count to 0. Call it and print st.count. Then change the parameter to const struct stats * and read what the compiler tells you.

  3. In parent_chain.c, add a function depth(const struct proc *p) that returns how many parents a process has. It should return 0 for init and 2 for edit. Do not use recursion the first time, then try it with recursion.

  4. What is sizeof each of these on 64-bit gcc, and why? Check your answers with a tiny program.

struct a { int x; };
struct b { int x; struct b *next; };
struct c { char name[40]; struct c *left, *right; };

What comes next

We now know what a pointer to a struct is, why -> exists and when to use it instead of a dot, why functions take struct pointers, and how a struct can point at another one of its own kind. In the kernel we saw current, the parent pointers in task_struct, the shared mm pointer, and chains like file->f_path.dentry->d_inode->i_ino.

Once structs can point at each other, you can build chains of them. We will keep building on that in the next posts.

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

Frequently asked questions

What is the arrow operator in C?

The arrow operator -> reaches a field of a struct through a pointer. p->id means the same as (*p).id. It first follows the pointer to the struct and then picks the field. Use it when you have a pointer to a struct, and use the dot when you have the struct itself.

What is the difference between the dot and the arrow in C?

The dot works on a struct variable, like s.id. The arrow works on a pointer to a struct, like p->id. If you use the wrong one, gcc gives an error. When a struct holds another struct by value, you can use both in one line, for example p->addr.pin.

Why is *p.id wrong for a pointer to a struct?

The dot binds tighter than the star, so *p.id is read as *(p.id). A pointer has no fields, so the compiler rejects it. You need brackets, (*p).id, or the shorter p->id.

Why does the Linux kernel use pointers to structs so much?

A pointer is a small fixed size, so passing it is cheap, and several users can share one struct instead of each holding a copy. The kernel also needs structs to refer to each other, like a task_struct pointing at its parent. A struct cannot contain itself, but it can hold a pointer to its own type.

What is current in the Linux kernel?

current is a pointer of type struct task_struct *. It points at the task that is running on the current CPU. Kernel code uses it with the arrow to reach that process, for example current->real_parent or current->fs.

What happens if you use the arrow operator on a NULL pointer?

The program reads memory near address 0, which is not allowed. In user space you get a segmentation fault. In the Linux kernel you get an oops, which is a crash report in the kernel log, and the system may stop working. Check a pointer that can be NULL before you use -> on it.

Continue with a course

Article notes

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

Topics