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

Answers to the kernel C exercises

Answers and reasoning

  1. x is 3 and p still points to x. q is a separate pointer variable; changing q itself changes neither its former target nor another alias.

  2. Forming a+4 is valid and useful as an iteration endpoint; dereferencing it as a[4] is invalid. The last element is a[3].

  3. No. value and the pointer value next are copied. Both next members refer to the same node; assignment does not establish ownership. Independently freeing two apparently copied chains can produce a double-free.

  4. Reading next after free accesses an object outside its lifetime. Safe order: keep old=head, advance head=old->next, then free(old). The chain must be acyclic.

  5. The parameter head is a copy of the pointer value. head=NULL changes only the local variable. Pass the address of the caller's variable to a function taking struct node **; that second-level pointer must also be valid.

  6. total becomes 5, 12, then 21; the caller's head remains A throughout sum. destroy sets head=B and frees A, then head=C and frees B, then head=NULL and frees C. An alias to B still targets a live node after A is freed, but cannot validly access B once B is freed. Saving next before free does not authorize every future use.

  7. Setting both produces 1010; clearing 0010 leaves 1000. When testing several bits, a nonzero AND result establishes at least one matching bit, not necessarily all of them.

  8. If allocation two fails, the first node remains live and must be freed. If allocation one fails, no node was created. The accompanying program returns early for the first failure and calls destroy on the first node for the second failure.

  9. Neither. NULLing one variable does not repair its aliases; every user's lifetime contract matters. volatile alone does not provide thread coordination or the required memory ordering.

A fresh repair question

head and saved both refer to A. destroy(&head) releases the entire chain. Why does head==NULL not establish that saved->value is safe? The condition reports only head's value; saved supplies no permission to access an object whose lifetime ended. A solution must prevent borrowed use after the lifetime ends, rather than merely modifying one pointer variable.

Return to the questions. Identify the cause of an error: value-copy confusion, array bounds, lifetime or ownership contract. Then retry with a fresh example.