Reading position, not mastery.
Reading settings
Line spacing
Text width
Saved only in this browser. Theme and colors are in Appearance.
Explore, understand, practice

C for reading kernels: data, pointers and lifetime

Why does the kernel learning path lead to C?

Suppose you must keep a thousand I/O requests. Each request has a state, buffer, length and link to another request. Reading the code requires knowing where the request object lives, who merely holds its address, and when access must stop. Syntax alone is insufficient: you must trace memory state changes.

Historically, C developed alongside Unix in the early 1970s, drawing on B and BCPL and combining machine-oriented operations with a type system. Dennis Ritchie's account places its emergence between 1969 and 1973. This history helps explain its place in systems study; it does not establish C as the only possible choice today. See Ritchie's history of C.

Lesson goals: trace a two-node chain by hand, distinguish copying an object from copying its address, and identify a use-after-free before execution. Allow six hours across three sessions: pointers and arrays; structures and lifetimes; worked example and practice. This is a focused introduction, not a complete C programming course.

Prerequisites and a quick diagnostic

You need assignment, functions, conditions and loops. int x = 4; initializes an integer; x = x + 1; replaces its value. A function body executes when called; return transfers control to the caller; if selects using zero or nonzero. If these are unfamiliar, first trace tiny examples of these operations on paper.

Predict: after int x=4; int y=x; y=9;, what is x? It remains 4 because the integer value was copied. We will ask the corresponding question for pointers.

1. Object, address and type are different things

Here an object is a region of storage holding a value, not necessarily an object in object-oriented programming. The name x refers to an object; &x produces its address. A pointer is a value that can refer to an object. Possessing it alone does not guarantee valid access: the object must be alive, correctly aligned and accessed through an appropriate type.

int x = 4;
int *p = &x;
int *q = p;
*q = 9;

In the declaration int *p, the star participates in declaring a pointer type. In the expression *q, it dereferences the pointer to access the target object. p and q are separate variables containing the same pointer value; x becomes 9. A later q = NULL; does not change p. Copying an address does not copy its target object.

NULL represents no target; dereferencing it is invalid. A cast changes type interpretation without creating a valid object. const int *p prevents writing the integer through this path; int * const p prevents changing the pointer itself. const is neither a lock nor a guarantee against changes through other aliases. See GNU C pointers.

2. An array has a length; a pointer need not carry it

int a[3] = {10, 20, 30};
int *p = a;
int second = *(p + 1);

second is 20. p+1 advances by one int element, not necessarily one byte. Array elements are contiguous. If sizeof(int) is four in a particular environment, the byte distance is four; that number is not a universal machine rule.

In many expressions, an array name converts to a pointer to its first element, but arrays and pointers are different types. In this scope, sizeof a measures the entire array; sizeof p measures the pointer. A function parameter declared as int a[] is adjusted to a pointer: this declaration does not communicate the length. Pass a separate length and respect its contract.

Forming the one-past pointer a+3 is permitted, but reading or writing a[3] is not. Keep pointer arithmetic within one array and its one-past position. A larger numeric address does not imply permission to access it. See pointers and arrays.

3. A struct names related data together

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

Each node contains a value and a pointer to the next node. next is not the next node itself. For struct node n, n.value selects a member; for struct node *p, p->value means (*p).value and requires a valid target. Alignment can introduce padding; do not replace sizeof(struct node) with a hand-added sum of member sizes.

struct node b = a; copies members. If a.next points to node C, b.next points to that same C. This is a shallow copy, not a recursive copy of the chain. See GNU C structures.

4. Lifetime, scope and ownership

Scope determines where a name can be used; lifetime determines when an object exists. An automatic object in a block normally reaches the end of its lifetime when execution leaves that block. A stack is the usual implementation, but C does not promise that every variable physically occupies stack RAM: a compiler can use a register or eliminate the variable.

Static objects live throughout program execution. Dynamically allocated storage lives from malloc until free, even if the allocating function returns. A local pointer can disappear without its allocation being automatically freed, producing a leak. Returning the address of an automatic local does not keep that object alive. See local variables and dynamic allocation.

Ownership is a program contract: who must release the allocation? Borrowing means temporary use without taking responsibility for freeing. C does not automatically enforce this contract. Here, the list owns its nodes while sum borrows access. Freeing a node does not NULL all its aliases. malloc is a user-space allocator; Linux kernel allocation has its own APIs and constraints. Do not paste malloc into kernel code. See kernel coding style and allocation.

Independent pointers into a chain and the end of the first node's lifetime

Figure: head owns the chain and alias borrows access. After A is freed, B can remain alive while using alias to access A is invalid. A and B are symbolic labels, not measured addresses.

5. Worked example: build, traverse and release

Read the complete user-space program. It takes no standard input, allocates nodes with values 10 and 20, prints their sum and releases them. It is single-threaded and models a list without directly using Linux's list API.

static int sum(const struct node *p)
{
    int total = 0;
    for (; p != NULL; p = p->next)
        total += p->value;
    return total;
}

static void destroy(struct node **head)
{
    while (*head != NULL) {
        struct node *old = *head;
        *head = old->next;
        free(old);
    }
}

sum receives a pointer by value; advancing its local p does not change the caller's head. Small values avoid total overflow; a general-purpose list would need a range contract or checked summation. destroy receives the address of the head variable: struct node ** lets it update the caller's head. Its contract requires head to address a valid pointer variable and the chain to be acyclic; outstanding borrows must not later access freed nodes.

Step head total in sum Live nodes
After construction A Not started A and B
Visiting A, value 10 A 10 A and B
Visiting B, value 20 A 30 A and B
First destroy iteration B sum has returned B only
End of destroy NULL — None

In destroy, read old->next before free, advance the list head, then free old. Replacing that sequence with free(old); *head = old->next; reads next from a dead object: use-after-free. Apparently unchanged bytes do not make the access valid. Undefined behavior means the language promises no particular result; a crash is only one possibility.

6. Bit flags and kernel expressions

unsigned int flags = 0;
const unsigned int READY = 1u << 2;
flags |= READY;
int ready = (flags & READY) != 0;
flags &= ~READY;

READY has low-bit pattern 0100. OR sets the bit; AND tests it; AND with its complement clears it. Bitwise & differs from logical &&; unary &x takes an address, distinguished by its operand count. Use unsigned in this model and keep a shift count below the type's bit width. Bit-based storage is not inherently atomic. volatile is neither a lock nor a memory barrier; the concurrency lesson returns to this. See the kernel volatile explanation.

7. Connecting to Linux's actual lists

Linux's common doubly linked list embeds a struct list_head inside its host object. The list is circular and uses a sentinel head, so reaching NULL is not its general termination condition. list_del unlinks an entry; freeing the host object is separate. container_of recovers a host from an embedded member; it cannot make an invalid pointer valid. Compare these APIs with the model using the official Linux list documentation. Linked lists are not always fastest: arrays can offer better locality.

8. Experiment and source-reading tools

Inside an environment with a C compiler:

cc -std=c11 -Wall -Wextra -Wpedantic -O0 -g list_demo.c -o list_demo
./list_demo
cc -std=c11 -Wall -Wextra -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer list_demo.c -o list_demo_checked
./list_demo_checked

First change to examples/002-c-foundations, or supply the full source path. Expected output is sum=30 followed by empty=yes on another line. No fixed address or sizeof value is assumed. expected-output.txt is a prediction, not an execution log. Sanitizers require compiler and runtime support; a clean report does not prove the absence of every defect. See GCC instrumentation.

When reading source, locate type declarations first, construction and release second, then field readers and writers. Search with rg -n 'struct node|malloc|free|destroy' list_demo.c; text matches do not replace alias and control-flow analysis. Analyze the broken sequence on paper rather than expecting a deterministic output.

Verification status: the example and allocation/release paths were reviewed as text. It has not been compiled or run here: no C compiler was found on PATH and no usable WSL distribution was available.

Independent practice and retrieval

  1. After int x=3; int *p=&x; int *q=p; q=NULL;, what are x and p?
  2. For int a[4];, are forming a+4 and reading a[4] both valid?
  3. If a node is copied by assignment, do the two next members point to independent nodes?
  4. Why is freeing head before reading head->next wrong? Write the safe order.
  5. Why does void clear(struct node *head) { head = NULL; } not clear the caller's variable?
  6. Tabulate sum and destroy for A(5) → B(7) → C(9). After freeing A, what is the status of an alias to B?
  7. Set flags 0010 and 1000, then clear only 0010. What remains?
  8. If allocation of node two fails, what must be freed? What if the first allocation fails?
  9. Does NULLing head after release make another alias safe? Does volatile prevent races?

Open the explained answers after attempting the questions.

Without notes, define object, pointer, alias, lifetime and owner in three minutes and write a safe deletion sequence. Before continuing, explain exercises 2, 4, 5, 6 and 8 correctly. For difficulty with 2, draw array boundaries; for 4 and 8, build an object-lifetime table; for 5, draw separate boxes for the local and caller pointer variables. Then retry an analogous example with new numbers. On the following day, trace a fresh three-node list; at the chapter review, also recall the previous lesson's mode-switch distinction. This is a review suggestion; no reminder automation was created.

Sources and navigation

Official sources above were searched on 2026-10-16. Linux, GCC and Ritchie's account were opened; full retrieval of the GNU pages timed out, leaving only their search-result descriptions accessible. GNU links are supplementary reading, not fully reviewed page text. Explanations, tables and examples are original instructional material.

Previous lesson · Course roadmap · فارسی. Next: The machine underneath the OS is now available. Available content does not imply that the learner has studied or mastered it.