C Programming • C17 baseline, standards-specific features labeled
Linked Lists and Ownership
Build a simple singly linked list while making allocation failure and cleanup explicit.
A linked list stores each value in a node that points to the next node. Insertion can be constant time at the head, but traversal is linear and nodes are separate allocations. The list owner must eventually release every node, including when later work fails.
Example
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
int push_front(struct node **head, int value) {
if (head == NULL) {
return 0;
}
struct node *item = malloc(sizeof *item);
if (item == NULL) {
return 0;
}
item->value = value;
item->next = *head;
*head = item;
return 1;
}
void free_list(struct node *head) {
while (head != NULL) {
struct node *next = head->next;
free(head);
head = next;
}
}
What to expect
Each successful push adds one owned node at the front; free_list releases every node exactly once.
Key idea: Document ownership and test empty lists, allocation failures, and repeated cleanup boundaries.