🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Student Records Linked List
Maintain student records in a sorted linked list and search by roll number.
Student Records Linked List in C
The last programming exercise of the structure chapter in this free C programming course asks for a program that maintains student records in a linked list and searches for a record by roll number. Each node holds a name, a roll number, marks and a link to the next node. It is the structure you would use for a table of registered devices, a list of open connections or a set of pending jobs in embedded C programming: records that come and go, looked up by an identifier.
The version in this lecture goes a step beyond the minimum. It keeps the list sorted by roll number while inserting, rejects duplicate roll numbers, copies names safely into a fixed-size field, and lets a search stop early when it passes the place where the roll number would have been. The whole program is original code that you can compile and run right now.
What You Will Learn
- How to insert into a sorted linked list using a pointer to a pointer
- How to reject duplicate keys at insertion time
- How to copy text into a fixed array with
snprintf()without overflow - How to search a sorted list and stop early
- How to modify a record through the pointer returned by a search
- How to free the whole list safely at the end
Prerequisites
You need self-referential structures, malloc()/free(), and a clear picture of pointers to pointers. If the double pointer looks scary, the diagram below shows exactly what it points at. This lecture is the final practical piece of the free embedded C course structure chapter.
The Student Node
The record has three data fields and one link. The name is a 20-byte array so that the node is self-contained: freeing the node frees the name too. The link is called next and points to another struct student, which is why the structure needs a tag name even if you later add a typedef.
Sorted Insertion with a Pointer to a Pointer
Inserting into a sorted list normally needs special code for the first position, because then the head pointer itself must change. A neat way to remove the special case is to keep a pointer to the link that will be rewritten. At the start that link is the head pointer. As you move along, it becomes the next member of the previous node. Either way, the final step is the same two assignments: point the new node at the node that follows, then store the new node through the link.
Duplicate detection comes for free. After the loop stops, the link points at the first node whose roll number is not smaller than the new one. If that node has the same roll number, the key already exists and the function returns an error before allocating anything.
| Return value | Meaning |
|---|---|
| 0 | Student added |
| -1 | Roll number already present, nothing changed |
| -2 | Memory allocation failed |
Safe Name Copying
Older code uses strcpy() to copy a name into the node, which overflows the array when the name is too long. The program uses snprintf(dst, sizeof dst, "%s", name) instead. It writes at most the size you give, always adds the terminating zero, and silently truncates anything longer. In the demonstration, “Venkata Subrahmanyam Rao” is cut to nineteen characters, and the program stays healthy.
Searching by Roll Number
A search walks the list comparing roll numbers. Because the list is sorted, the loop can stop as soon as it reaches a roll number larger than the one it wants: the target cannot appear later. That makes unsuccessful searches faster on average. The function returns a pointer to the node, or NULL when there is no such student, and the caller must check for NULL before using the result.
The Complete Program
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[20];
int roll;
int marks;
struct student *next;
};
/* Keep the list sorted by roll number. Refuse duplicates. */
static int add_student(struct student **head, const char *name, int roll, int marks)
{
struct student **link = head;
while (*link && (*link)->roll < roll) {
link = &(*link)->next;
}
if (*link && (*link)->roll == roll) {
return -1; /* duplicate roll number */
}
struct student *s = malloc(sizeof *s);
if (!s) {
return -2;
}
snprintf(s->name, sizeof s->name, "%s", name); /* truncates, never overflows */
s->roll = roll;
s->marks = marks;
s->next = *link;
*link = s;
return 0;
}
static struct student *find_by_roll(struct student *head, int roll)
{
for (; head && head->roll <= roll; head = head->next) {
if (head->roll == roll) {
return head;
}
}
return NULL; /* sorted list lets us stop early */
}
static void print_all(const struct student *s)
{
printf("%-6s %-20s %5s\n", "roll", "name", "marks");
for (; s; s = s->next) {
printf("%-6d %-20s %5d\n", s->roll, s->name, s->marks);
}
}
static void free_all(struct student *s)
{
while (s) {
struct student *next = s->next;
free(s);
s = next;
}
}
int main(void)
{
struct student *class_list = NULL;
add_student(&class_list, "Latha", 23, 81);
add_student(&class_list, "Imran", 7, 67);
add_student(&class_list, "Sunil", 15, 90);
add_student(&class_list, "Kavya", 3, 74);
add_student(&class_list, "Venkata Subrahmanyam Rao", 31, 58);
if (add_student(&class_list, "Imran Again", 7, 99) == -1) {
puts("rejected: roll 7 already exists\n");
}
print_all(class_list);
int probes[] = {15, 99};
for (size_t i = 0; i < 2; i++) {
struct student *hit = find_by_roll(class_list, probes[i]);
if (hit) {
printf("\nroll %d -> %s, marks %d\n", probes[i], hit->name, hit->marks);
} else {
printf("\nroll %d -> not found\n", probes[i]);
}
}
struct student *who = find_by_roll(class_list, 23);
if (who) {
who->marks += 5; /* update through the returned pointer */
printf("\nafter grace marks: %s has %d\n", who->name, who->marks);
}
free_all(class_list);
return 0;
}Build and Run
gcc -std=c11 -Wall -Wextra -o ep_students ep_students.c
./ep_studentsrejected: roll 7 already exists
roll name marks
3 Kavya 74
7 Imran 67
15 Sunil 90
23 Latha 81
31 Venkata Subrahmanya 58
roll 15 -> Sunil, marks 90
roll 99 -> not found
after grace marks: Latha has 86The students were added in the order 23, 7, 15, 3, 31, yet they are printed in ascending order of roll number. The duplicate roll 7 is rejected with a message, roll 15 is found, roll 99 is not, and finally the pointer returned by the search is used to add five grace marks to roll 23, raising it from 81 to 86.
Modifying a Record Through the Search Result
Because find_by_roll() returns a pointer to the real node, not a copy, changing who->marks changes the stored record. This is a feature, but it has a lifetime rule: the pointer is valid only until the node is freed. If you delete a student and keep using an older pointer to it, you are reading freed memory. For a small program, use the pointer immediately and drop it.
Try It Yourself
Extend the program with a remove_student() function. Walk with a pointer to the link until you find the matching roll number, copy the node’s next into the link, and free the node. Then add a function that prints only the students whose marks are below a pass threshold, and one that returns the topper by scanning the list once, the same single-pass idea from the previous lecture. Finally, replace malloc() with a static array of ten nodes and a small free list, which is how many real-time systems avoid heap allocation altogether.
Common Mistakes and Troubleshooting
| Mistake | Symptom | Fix |
|---|---|---|
Using strcpy for names | Overflow on long names | Use snprintf with sizeof |
| Special-casing the head separately | More code and more bugs | Use a pointer to the link |
Forgetting to test the search result for NULL | Crash on a missing roll number | Check before dereferencing |
| Allowing duplicate roll numbers | Searches return the wrong student | Detect equality during insertion |
| Freeing a node but keeping its pointer | Use after free | Set the pointer to NULL or stop using it |
Comparing roll numbers with <= in the wrong place | Duplicate inserted or last node skipped | Test with first, middle, last and duplicate inserts |
Warning:
Do not read the roll number of *link without first checking that *link is not NULL. The loop condition in add_student() tests the pointer first and the value second for exactly this reason.
Best Practices
- Keep one function per operation: add, find, print, free.
- Return status codes from operations that can fail, and check them.
- Make read-only functions take
constpointers. - Document who owns each node and when a returned pointer stops being valid.
- In firmware, replace
mallocwith a fixed pool of nodes so allocation can never fail at run time.
Performance and security notes:
Searching a sorted linked list is still O(n), so for thousands of records use a hash table or a sorted array with binary search. Sizing the name field and truncating on input prevents an attacker-controlled name from corrupting memory next to the node.
Summary and Key Takeaways
- A pointer to the link removes the special case for inserting at the head.
- A sorted list lets you reject duplicates and end searches early.
snprintfis the safe way to fill a fixed text field.- A search returns a pointer to the real node, valid until it is freed.
- Always free the entire list before the program ends.
Conclusion
You have built a complete record manager with a sorted insertion, a duplicate guard, a bounded text copy and a search. Together with the earlier exercises you now have the full set of structure-chapter skills. The final lecture of this series explains the answer key of the chapter, why some programs fail to compile, and finishes with a quiz and interview questions for the free C programming course.
Frequently Asked Questions
Why use a pointer to a pointer in add_student?
It lets the same code update either the head pointer or a node’s next pointer, so inserting at the front is not a special case.
Why keep the list sorted?
Sorted order makes duplicates easy to detect and lets searches stop early. The price is a slightly slower insertion.
What does snprintf do when the name is too long?
It copies only what fits, ends the text with a zero byte, and ignores the rest.
Can two students share a roll number?
Not in this design. The insert function rejects the second one.
How would I delete a student?
Walk with a pointer to the link, unlink the node by assigning the node’s next to the link, then free the node.
Can I use an array of students instead?
Yes, and for fixed small tables it is simpler. A list wins when records are frequently added and removed in the middle.
Keep Learning C for Free
One more lecture to finish the structure chapter: answer key, quiz and interview questions.

2 Comments