🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Delete Node from Linked List
Remove the first, a middle or the last node of a singly linked list in C, and release its memory with free() without losing the rest of the list.
Welcome back to our free C programming course. Adding nodes is half the story; a list that can only grow will eventually eat all your memory. In this lecture you will learn how to delete a node from a linked list in C, which has two jobs: unlink the node so the list skips it, then free() it so its memory returns to the allocator. Forgetting either job gives you a classic bug. This free C tutorial shows three versions of deletion, the safe ordering rules, and why embedded C programming teams treat a dangling pointer as a serious defect.
What You Will Learn
- The two-step meaning of deletion: unlink, then free
- How to remove the first node and why head must be updated
- How to remove a middle or last node using the previous node
- A single pointer-to-pointer routine that deletes by value at any position
- How to avoid memory leaks, use-after-free and double free
Prerequisites
You need the node_t structure, append() and free_list() from the previous lectures, plus a working understanding of what free() does and does not do to a pointer variable. If pointer-to-pointer still feels shaky, re-read the earlier chapter of this free embedded C course first.
Unlink First, Then Free
Changing a few pointers removes a node from the logical list, but the bytes you obtained from malloc() are still reserved for you. Nobody else can use them until you call free(). That is why deletion always has two stages. Unlinking alone leaks memory. Freeing without unlinking leaves a pointer inside the list aimed at memory that no longer belongs to you, a dangling pointer that will crash or silently corrupt data the next time someone walks the list.
next pointer, its value) before you call free(). After free(), reading dead->next is undefined behaviour even though it often seems to work.Case 1: Delete the First Node
The first node has no predecessor. The only thing pointing at it is the head variable, so the head is what must change. Remember the victim in a temporary, move the head to the second node, and free the victim.
Delete first node: head skips 10
Case 2: Delete a Middle or Last Node
Here you do have a predecessor, and it is the node that must change. Stand on the node before the victim, call it prev. The victim is prev->next. Copy the victim’s own next into prev->next to bypass it, then free the victim.
Delete the node after prev (bypass, then free)
If the victim is the last node, its next is already NULL. Copying it into prev->next makes prev the new last node automatically; again there is no separate branch.
| Case | Pointer that changes | Code idea |
|---|---|---|
| First node | The head variable | head = dead->next |
| Middle node | prev->next | prev->next = dead->next |
| Last node | prev->next (becomes NULL) | prev->next = dead->next |
| Only node | The head variable (becomes NULL) | head = dead->next |
One Routine for All Positions
You can fold the two cases into one function with the pointer-to-pointer walk from the previous lecture. Let pp hold the address of whichever slot points at the current node: first the head variable, then each next field. When (*pp)->value matches the key, the slot *pp is exactly the pointer that needs to change, whether it is the head or somebody’s next. Assign *pp = dead->next and free. The first-node case and the middle case become literally the same line.
Complete Delete Node Program
The code below provides pop_front(), delete_after() and delete_value(), then deletes from the front, the middle and the end, tries a missing key, drains the list, and finally confirms that popping an empty list is refused.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value;
struct node *next;
} node_t;
static node_t *make_node(int value)
{
node_t *n = malloc(sizeof *n);
if (n == NULL)
return NULL;
n->value = value;
n->next = NULL;
return n;
}
static void print_list(const node_t *head)
{
for (const node_t *p = head; p != NULL; p = p->next)
printf("%d -> ", p->value);
printf("NULL\n");
}
static void free_list(node_t *head)
{
while (head != NULL) {
node_t *next = head->next;
free(head);
head = next;
}
}
static int append(node_t **head, int value)
{
node_t *n = make_node(value);
if (n == NULL)
return -1;
node_t **pp = head;
while (*pp != NULL)
pp = &(*pp)->next;
*pp = n;
return 0;
}
/* remove the first node, hand its value back through *out */
static int pop_front(node_t **head, int *out)
{
if (*head == NULL)
return -1;
node_t *dead = *head; /* remember the victim */
*out = dead->value;
*head = dead->next; /* second node becomes first */
free(dead); /* give the memory back */
return 0;
}
/* remove the node that follows 'prev' (middle or last node) */
static int delete_after(node_t *prev)
{
if (prev == NULL || prev->next == NULL)
return -1;
node_t *dead = prev->next;
prev->next = dead->next; /* bypass; for the last node this stores NULL */
free(dead);
return 0;
}
/* remove the first node holding 'key' - one code path for every position */
static int delete_value(node_t **head, int key)
{
for (node_t **pp = head; *pp != NULL; pp = &(*pp)->next) {
if ((*pp)->value == key) {
node_t *dead = *pp;
*pp = dead->next;
free(dead);
return 0;
}
}
return -1;
}
int main(void)
{
node_t *head = NULL;
int v;
for (int i = 10; i <= 50; i += 10)
append(&head, i);
print_list(head);
if (pop_front(&head, &v) == 0)
printf("popped %d\n", v);
print_list(head);
delete_after(head); /* removes 30, the node after 20 */
print_list(head);
delete_value(&head, 50); /* last node */
print_list(head);
if (delete_value(&head, 99) != 0)
printf("99 not in list\n");
while (pop_front(&head, &v) == 0)
printf("drained %d\n", v);
print_list(head);
if (pop_front(&head, &v) != 0)
printf("pop on empty list refused\n");
free_list(head);
return 0;
}
Build and run
gcc -std=c11 -Wall -Wextra -g -fsanitize=address,undefined -o ll_delete ll33.c
./ll_delete
Expected output:
10 -> 20 -> 30 -> 40 -> 50 -> NULL
popped 10
20 -> 30 -> 40 -> 50 -> NULL
20 -> 40 -> 50 -> NULL
20 -> 40 -> NULL
99 not in list
drained 20
drained 40
NULL
pop on empty list refused
The sanitizer stays quiet: no leaks, no use-after-free, no double free. If you remove a free(dead) line and run again, AddressSanitizer will report the lost node at program exit. That is a very effective way to learn.
Common Mistakes in Linked List Deletion
| Mistake | Consequence | Fix |
|---|---|---|
| free(node) before saving node->next | Use-after-free, lost rest of list | Copy next first, then free |
| Unlink without free | Memory leak | Always pair unlink with free |
| Deleting the head but not updating it | Head dangles | Write head = dead->next |
| Not checking prev->next for NULL | Crash when deleting after the last node | Return an error when nothing to delete |
| Freeing the same node twice | Heap corruption | Remove it from the list first; never keep a second pointer to it |
| Deleting inside a for loop that advances with p = p->next | Reads freed memory | Save next before deleting, or use the pointer-to-pointer pattern |
Best Practices, Safety and Performance
- Decide who owns each node. The list owns it; callers get values, not pointers they might free.
- Return the removed value or an error code so callers can react.
- Delete by value is O(n) because it must search. Delete after a known node is O(1).
- In embedded C programming, a freed node in a static pool should be pushed to a free-list, not passed to
free(); you will build that in the lab. - Security: use-after-free bugs are a well-known source of exploitable vulnerabilities. Treat them as seriously as buffer overflows.
- Some teams set the pointer to NULL after free where practical, which turns a silent bug into an immediate, debuggable crash.
Summary and Key Takeaways
- Deletion is unlink plus free, in that order.
- First node: move the head. Other nodes: change the previous node’s next.
- A pointer-to-pointer walk handles every position with one code path.
- Run with AddressSanitizer to catch leaks and dangling pointers early.
You now know insertion and deletion, the heart of this free C programming course chapter on linked lists. Next you will assemble them into a complete menu-style program.
Frequently Asked Questions
How do you delete a node from a singly linked list in C?
Find the node before it, set that node’s next to the victim’s next, then free the victim. For the first node, move the head instead.
Why must I free the node after unlinking it?
Unlinking only removes it from the list. The memory stays reserved until you call free(), so skipping it causes a leak.
What is a dangling pointer?
A pointer that still holds the address of memory that has been freed. Using it is undefined behaviour.
Can I delete the last node without a special case?
Yes. Its next is NULL, so copying that into the previous node’s next makes the previous node the new last node.
Is deleting from a linked list faster than from an array?
The unlink is O(1) because nothing shifts, but finding the node is O(n). Arrays shift elements instead.
Should embedded C programming use free() for list nodes?
Often not. Many firmware projects avoid the heap and recycle nodes through a static pool for predictable timing.
Continue the Free C Tutorial
Next up: assemble creation, insertion, deletion and search into one complete program.

2 Comments