SyntaxPilot
Courses/C Programming/Lesson 28

C Programming · Lesson 28 of 30 · 13 min

Capstone: student record system

queued

These are the notes for C episode 28, the capstone of the C course. A school office keeps its students in a paper register, and the principal wants a program. You write the obvious version first (three fixed arrays and a scanf loop) and watch it lose data in two ways. Then you fix it piece by piece with things you already know: a struct for one record, a dynamic array that grows with realloc, a file that remembers, safe input for names with spaces, a menu loop with switch, search with qsort and bsearch, update, delete, a report, and finally a split into student.h, student.c and main.c. Every example was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13.3, glibc 2.39, the same command as the SyntaxPilot compiler) and run with exactly the input shown. The online compiler runs each program in a fresh, empty folder, so files never survive from one run to the next there.

The problem: the school office register

Real-life example: the paper register. One line per student: roll number, name, marks. 600 students. A parent phones: "marks of roll 342?" and the clerk flips page after page. Tea spills on page 12. And the register is full: there's no line for the new admission. The principal says: make it a program.

A record is all the facts about one thing, here one student: roll, name, marks. A record system stores many records and lets you add, list, search, update and delete them.

Version 1: the obvious program

Three arrays of 100 and a loop that reads students until the input ends:

#include <stdio.h>

int main() {
    int roll[100];
    char name[100][20];
    float marks[100];
    int n = 0;
    while (scanf("%d %19s %f", &roll[n], name[n], &marks[n]) == 3)
        n++;
    printf("Students on file: %d\n", n);
    if (n > 0) {
        printf("First: %d %s %.1f\n", roll[0], name[0], marks[0]);
        printf("Last:  %d %s %.1f\n", roll[n - 1], name[n - 1], marks[n - 1]);
    }
    return 0;
}

Input (the stdin box):

101 Aman 72
102 Sana 88
103 Kabir 64
Students on file: 3
First: 101 Aman 72.0
Last:  103 Kabir 64.0

It works. Next morning the clerk runs it again to look up Aman (nothing typed yet):

Students on file: 0

Yesterday's students are gone. Then admission season: 101 students, roll 101 to 201.

Input (the stdin box):

101 Aman 72
102 Sana 55
103 Kabir 62
...            (97 more lines)
200 Tara 61
201 Zoya 91
Students on file: 101
First: 101  0.0
Last:  201 Zoya 91.0

No error, wrong data. Aman (the first student) lost his name and marks. The 101st student was written to roll[100], name[100] and marks[100], which don't exist, so the values landed on other arrays in memory, right on top of Aman. (Where exactly they land depends on the compiler: that's undefined behaviour.)

Why version 1 failed

  1. Fixed size. roll[100] can't grow, and C never checks the end of an array: student 101 overwrites other data.
  2. RAM forgets. Every variable lives in RAM (the computer's working memory), which is handed back when the program ends.
  3. Three separate arrays. One student is split across three places; it's easy to sort or delete in one array and forget the others.
Problem Fix (episode)
One student in three arrays a struct (episode 12)
Fixed size a dynamic array with realloc (episode 14)
RAM forgets a file (episode 15)

One record = one struct, in an array that grows

Real-life example: one line of the register = one struct. When the register is full, the office buys a new one twice as thick and copies the names across. That's realloc with capacity doubling. An array that grows while the program runs is a dynamic array.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int roll;
    char name[50];
    float marks;
} Student;

Student *list = NULL;
int n = 0, cap = 0;

int add(Student s) {
    if (n == cap) {
        int newcap = (cap == 0) ? 4 : cap * 2;
        Student *bigger = realloc(list, newcap * sizeof(Student));
        if (bigger == NULL) return 0;
        list = bigger;
        cap = newcap;
        printf("grew to %d slots\n", cap);
    }
    list[n++] = s;
    return 1;
}

int main() {
    for (int i = 0; i < 1000; i++) {
        Student s = {101 + i, "Student", 50};
        add(s);
    }
    printf("%d students, %d slots, %zu bytes each\n", n, cap, sizeof(Student));
    free(list);
    return 0;
}
grew to 4 slots
grew to 8 slots
grew to 16 slots
grew to 32 slots
grew to 64 slots
grew to 128 slots
grew to 256 slots
grew to 512 slots
grew to 1024 slots
1000 students, 1024 slots, 60 bytes each
  • list points to the students on the heap (episode 14).
  • n = how many students are stored; cap (capacity) = how many slots are rented. Always n <= cap.
  • When n == cap, the new capacity is 4 the first time, then double.
  • realloc goes into a temporary pointer bigger. If it returns NULL, the old block is still valid; writing list = realloc(list, ...) directly would lose (leak) it on failure.

Why double, and not +1?

realloc may have to move the whole block to a new place and copy every student. Growing by one slot could do that on every add: for 1,000 students, up to 1 + 2 + … + 999 ≈ 500,000 student copies. Doubling grows only 9 times (4 → 1024) and copies about 4 + 8 + … + 512 ≈ 1,000 students in total. The price: up to half of the slots may sit empty. Adding one item is O(1) on average (amortised constant time).

Save and load: the almirah

Real-life example: at night the register goes into the office almirah, so it's still there tomorrow. In C, that's a file on the disk (episode 15). We save the whole array in binary with one fwrite, and read it back one student at a time with fread:

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int roll;
    char name[50];
    float marks;
} Student;

Student *list = NULL;
int n = 0, cap = 0;

int add(Student s) {
    if (n == cap) {
        int newcap = (cap == 0) ? 4 : cap * 2;
        Student *bigger = realloc(list, newcap * sizeof(Student));
        if (bigger == NULL) return 0;
        list = bigger;
        cap = newcap;
    }
    list[n++] = s;
    return 1;
}

int save(const char *file) {
    FILE *f = fopen(file, "wb");
    if (f == NULL) { perror(file); return 0; }
    fwrite(list, sizeof(Student), n, f);
    fclose(f);
    return 1;
}

int load(const char *file) {
    FILE *f = fopen(file, "rb");
    if (f == NULL) return 0;
    Student s;
    while (fread(&s, sizeof(Student), 1, f) == 1)
        add(s);
    fclose(f);
    return 1;
}

void free_all(void) {
    free(list);
    list = NULL;
    n = cap = 0;
}

int main() {
    Student a = {101, "Aman Verma", 72}, b = {102, "Sana Khan", 88};
    add(a);
    add(b);
    save("students.dat");
    free_all();
    printf("After free: %d students in memory\n", n);
    if (load("students.dat"))
        printf("Loaded %d students from the file\n", n);
    for (int i = 0; i < n; i++)
        printf("%d %s %.1f\n", list[i].roll, list[i].name, list[i].marks);
    free_all();
    return 0;
}
After free: 0 students in memory
Loaded 2 students from the file
101 Aman Verma 72.0
102 Sana Khan 88.0
  • "wb" = write binary (create or wipe the file), "rb" = read binary.
  • fwrite(list, sizeof(Student), n, f) writes n records of 60 bytes each, so students.dat is 120 bytes for two students.
  • load returns 0 if the file doesn't exist: that's not an error, it's the first day.
  • fread returns how many records it really read, so the loop stops at the end of the file. Each record goes through add, so the array grows as needed.

About the online compiler: every run starts in a fresh, empty folder, so a file can't survive to the next run there. That's why the demo plays "the night" inside one run: save, free_all() (as if the program had ended), then load. On your own computer, the second run of the final program really loads what the first one saved (shown below).

A binary file depends on the exact struct layout. If you change Student (say name[50] → name[60]), old files won't load correctly. A text file (practice question 2) is readable in any editor and survives such changes.

Typing names: three input bugs

Reading one student from the keyboard, with a name box of 20 chars:

#include <stdio.h>

int main() {
    int roll;
    char name[20];
    float marks = 0;
    printf("Roll: ");
    scanf("%d", &roll);
    printf("Name: ");
    scanf("%s", name);
    printf("Marks: ");
    scanf("%f", &marks);
    printf("\nSaved: %d | %s | %.1f\n", roll, name, marks);
    return 0;
}

Input (the stdin box):

101
Aman Verma
85
Roll: Name: Marks: 
Saved: 101 | Aman | 0.0

Bug 1: %s stops at the first space. Only Aman went into name. Then scanf("%f") found the word Verma instead of a number, failed, and left marks at 0. (Real-life: a hotel clerk who writes only "Ravi" when the guest says "Ravi Kumar".)

The obvious fix, fgets (it reads a whole line, spaces included):

    fgets(name, sizeof name, stdin);
Roll: Name: Marks: 
Saved: 101 | 
 | 0.0

Bug 2: the leftover newline. scanf("%d") read 101 but left the Enter key, a newline character '\n', waiting in the input. fgets read that as a complete, empty line, so name is just "\n".

The scanf way:

    scanf(" %[^\n]", name);
Roll: Name: Marks: 
Saved: 101 | Aman Verma | 85.0
  • The leading space in " %[^\n]" skips any spaces and newlines first (including the leftover one).
  • %[^\n] is a scanset: read every character that is not a newline.

Bug 3: buffer overflow. The box holds 20 chars. Input 102, Venkata Lakshmi Narasimha Rao (29 characters), 90:

*** stack smashing detected ***: terminated

(Status in the online compiler: Runtime Error (SIGABRT); nothing else prints because the program was killed before its output was flushed.) With no width, scanf writes the whole name past the end of the array: a buffer overflow, the same mistake as version 1. gcc's stack protector noticed the damaged memory and stopped the program.

The fix: a bigger box and a width one less than the box (room for the '\0' that ends every string):

#include <stdio.h>

int main() {
    int roll;
    char name[50];
    float marks = 0;
    printf("Roll: ");
    scanf("%d", &roll);
    printf("Name: ");
    scanf(" %49[^\n]", name);
    printf("Marks: ");
    scanf("%f", &marks);
    printf("\nSaved: %d | %s | %.1f\n", roll, name, marks);
    return 0;
}
Roll: Name: Marks: 
Saved: 102 | Venkata Lakshmi Narasimha Rao | 90.0
Read a name with What happens
scanf("%s", name) stops at a space; no limit → overflow risk
fgets(name, 50, stdin) right after scanf reads the leftover '\n': empty name (and keeps the '\n' at the end of a real line)
scanf(" %[^\n]", name) whole line, but no limit → overflow risk
scanf(" %49[^\n]", name) with char name[50] skips old newlines, reads the whole line, at most 49 chars ✔

(The fgets route also works if you first throw away the rest of the line, e.g. while (getchar() != '\n');, then remove the trailing newline with name[strcspn(name, "\n")] = '\0';.)

A menu loop with switch

Real-life example: an ATM screen. It shows the choices, does the one you press, and comes back to the menu until you choose exit. That's a menu loop: a loop around a switch (episode 5).

    int choice, roll;
    Student s, *p;
    do {
        printf("> ");
        if (scanf("%d", &choice) != 1) break;
        switch (choice) {
        case 1:
            if (scanf("%d %49[^\n] %f", &s.roll, s.name, &s.marks) == 3 && add(s))
                printf("Added %d\n", s.roll);
            else
                printf("Not added\n");
            break;
        ...
        case 0:
            if (save("students.dat")) printf("Saved %d students. Bye!\n", n);
            break;
        default:
            printf("No such option\n");
        }
    } while (choice != 0);
  • do ... while (choice != 0) runs the menu at least once.
  • If scanf("%d", &choice) can't read a number (the input ended, or a letter was typed), break leaves the loop instead of spinning forever.
  • switch jumps to the matching case; every case ends with break, or it falls through into the next case.
  • Case 1 reads roll, name and marks in one call: "%d %49[^\n] %f".

Search by roll, and a real bug

find uses bsearch (episode 25) with a safe comparator. add refuses a roll number that already exists. This is the first version, before the bug was found:

Student *find(int roll) {
    Student key = {roll};
    return bsearch(&key, list, n, sizeof(Student), by_roll);
}

int add(Student s) {
    if (find(s.roll) != NULL) return 0;   // roll already used
    if (n == cap) {
        int newcap = (cap == 0) ? 4 : cap * 2;
        Student *bigger = realloc(list, newcap * sizeof(Student));
        if (bigger == NULL) return 0;
        list = bigger;
        cap = newcap;
    }
    list[n++] = s;
    return 1;
}

The full program (MENU_BUG: the final program below without the qsort line in add), with the clerk's input: add Zoya 105, Aman 101, Kabir 103, list, search 105, exit:

Input (the stdin box):

1
105
Zoya Ahmed
91
1
101
Aman Verma
72
1
103
Kabir Singh
64
2
3
105
0
No saved file yet: starting empty
1 add, 2 list, 3 search, 4 update, 5 delete, 6 report, 0 save+exit
> Added 105
> Added 101
> Added 103
> 3 students
  105  Zoya Ahmed    91.0
  101  Aman Verma    72.0
  103  Kabir Singh   64.0
> Roll 105 not found
> Saved 3 students. Bye!

The input isn't echoed, so each > is one menu choice. Roll 105 is in the list, and search says it isn't there. No error, wrong answer.

Why: the array is in typing order, 105, 101, 103. bsearch checks the middle (101): 101 < 105, so the answer "must be" to the right. 103 < 105, right again. Nothing left: not found. Binary search trusts that the array is sorted, but add just puts each student at the end. The duplicate check in add had the same hidden bug.

The fix: one line at the end of add: sort by roll with the same comparator bsearch uses.

    qsort(list, n, sizeof(Student), by_roll);   // keep it sorted

Same input:

No saved file yet: starting empty
1 add, 2 list, 3 search, 4 update, 5 delete, 6 report, 0 save+exit
> Added 105
> Added 101
> Added 103
> 3 students
  101  Aman Verma    72.0
  103  Kabir Singh   64.0
  105  Zoya Ahmed    91.0
> 105: Zoya Ahmed, 91.0
> Saved 3 students. Bye!

For a school, qsort after every add is plenty fast. For millions of records, slide the new student into its place instead (like insertion sort), which keeps the array sorted in O(n) per add.

Update and delete

Real-life example: when a student leaves, the clerk doesn't leave a blank line; everyone below moves up one line.

int delete_roll(int roll) {
    Student *p = find(roll);
    if (p == NULL) return 0;
    for (int i = p - list; i < n - 1; i++)
        list[i] = list[i + 1];   // everyone below moves up
    n--;
    return 1;
}

// case 4, update:
p = find(roll);
if (p && scanf("%f", &p->marks) == 1) ...
  • p - list turns the pointer from find into an index (episode 11).
  • Delete copies each later student one place up, then n--. No gaps, and the array stays sorted.
  • Update: find returns a pointer into the array, so scanf("%f", &p->marks) changes the record in place.
  • After an add, realloc may move the array and qsort shuffles it, so an old pointer may point to the wrong place (a stale pointer). Call find again.

The report: average and topper

void report(void) {
    if (n == 0) { printf("No students yet\n"); return; }
    float sum = 0;
    int top = 0;
    for (int i = 0; i < n; i++) {
        sum += list[i].marks;
        if (list[i].marks > list[top].marks) top = i;
    }
    printf("Students: %d, average: %.2f\n", n, sum / n);
    printf("Topper: %s (%.1f)\n", list[top].name, list[top].marks);
}
  • If there are no students, say so instead of dividing by zero.
  • top remembers the index of the highest marks so far; on a tie the first one stays.

The finished program

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int roll;
    char name[50];
    float marks;
} Student;

Student *list = NULL;   // the dynamic array
int n = 0, cap = 0;     // students stored, slots rented
int by_roll(const void *a, const void *b) {
    const Student *x = a, *y = b;
    return (x->roll > y->roll) - (x->roll < y->roll);
}

Student *find(int roll) {
    Student key = {roll};
    return bsearch(&key, list, n, sizeof(Student), by_roll);
}

int add(Student s) {
    if (find(s.roll) != NULL) return 0;   // roll already used
    if (n == cap) {
        int newcap = (cap == 0) ? 4 : cap * 2;
        Student *bigger = realloc(list, newcap * sizeof(Student));
        if (bigger == NULL) return 0;
        list = bigger;
        cap = newcap;
    }
    list[n++] = s;
    qsort(list, n, sizeof(Student), by_roll);   // keep it sorted
    return 1;
}

int delete_roll(int roll) {
    Student *p = find(roll);
    if (p == NULL) return 0;
    for (int i = p - list; i < n - 1; i++)
        list[i] = list[i + 1];   // everyone below moves up
    n--;
    return 1;
}

void list_all(void) {
    printf("%d students\n", n);
    for (int i = 0; i < n; i++)
        printf("  %d  %-12s %5.1f\n", list[i].roll, list[i].name, list[i].marks);
}

void report(void) {
    if (n == 0) { printf("No students yet\n"); return; }
    float sum = 0;
    int top = 0;
    for (int i = 0; i < n; i++) {
        sum += list[i].marks;
        if (list[i].marks > list[top].marks) top = i;
    }
    printf("Students: %d, average: %.2f\n", n, sum / n);
    printf("Topper: %s (%.1f)\n", list[top].name, list[top].marks);
}

int save(const char *file) {
    FILE *f = fopen(file, "wb");
    if (f == NULL) { perror(file); return 0; }
    fwrite(list, sizeof(Student), n, f);
    fclose(f);
    return 1;
}

int load(const char *file) {
    FILE *f = fopen(file, "rb");
    if (f == NULL) return 0;
    Student s;
    while (fread(&s, sizeof(Student), 1, f) == 1)
        add(s);
    fclose(f);
    return 1;
}
int main() {
    if (load("students.dat")) printf("Loaded %d students\n", n);
    else printf("No saved file yet: starting empty\n");
    printf("1 add, 2 list, 3 search, 4 update, 5 delete, 6 report, 0 save+exit\n");
    int choice, roll;
    Student s, *p;
    do {
        printf("> ");
        if (scanf("%d", &choice) != 1) break;
        switch (choice) {
        case 1:
            if (scanf("%d %49[^\n] %f", &s.roll, s.name, &s.marks) == 3 && add(s))
                printf("Added %d\n", s.roll);
            else
                printf("Not added\n");
            break;
        case 2:
            list_all();
            break;
        case 3:
            scanf("%d", &roll);
            p = find(roll);
            if (p) printf("%d: %s, %.1f\n", p->roll, p->name, p->marks);
            else printf("Roll %d not found\n", roll);
            break;
        case 4:
            scanf("%d", &roll);
            p = find(roll);
            if (p && scanf("%f", &p->marks) == 1) printf("Updated %d\n", roll);
            else printf("Roll %d not found\n", roll);
            break;
        case 5:
            scanf("%d", &roll);
            if (delete_roll(roll)) printf("Deleted %d\n", roll);
            else printf("Roll %d not found\n", roll);
            break;
        case 6:
            report();
            break;
        case 0:
            if (save("students.dat")) printf("Saved %d students. Bye!\n", n);
            break;
        default:
            printf("No such option\n");
        }
    } while (choice != 0);
    free(list);
    return 0;
}

A full working day: add three students, try roll 101 again, search 103, update 103 to 79, delete 101, list, report, save:

Input (the stdin box):

1
105
Zoya Ahmed
91
1
101
Aman Verma
72
1
103
Kabir Singh
64
1
101
Aman Again
50
3
103
4
103 79
5
101
2
6
0
No saved file yet: starting empty
1 add, 2 list, 3 search, 4 update, 5 delete, 6 report, 0 save+exit
> Added 105
> Added 101
> Added 103
> Not added
> 103: Kabir Singh, 64.0
> Updated 103
> Deleted 101
> 2 students
  103  Kabir Singh   79.0
  105  Zoya Ahmed    91.0
> Students: 2, average: 85.00
Topper: Zoya Ahmed (91.0)
> Saved 2 students. Bye!

On your own computer, run it again in the same folder (input 2, 6, 0). The file from the first run is loaded:

Loaded 2 students
1 add, 2 list, 3 search, 4 update, 5 delete, 6 report, 0 save+exit
> 2 students
  103  Kabir Singh   79.0
  105  Zoya Ahmed    91.0
> Students: 2, average: 85.00
Topper: Zoya Ahmed (91.0)
> Saved 2 students. Bye!

Splitting into files

In episode 20 we split a program like a restaurant: the header (student.h) is the menu card, student.c is the kitchen, and main.c is the waiter. The online compiler takes a single file, so these three files are for your own computer.

student.h: the struct and one declaration per function, inside an include guard:

#ifndef STUDENT_H
#define STUDENT_H

typedef struct {
    int roll;
    char name[50];
    float marks;
} Student;

int add(Student s);
Student *find(int roll);
int delete_roll(int roll);
int count(void);
void list_all(void);
void report(void);
int save(const char *file);
int load(const char *file);
void free_all(void);

#endif

student.c: all the code. list, n and cap are static (episode 17), so they're private to this file; count() lets main.c ask how many students there are.

#include <stdio.h>
#include <stdlib.h>
#include "student.h"

static Student *list = NULL;   // private to this file
static int n = 0, cap = 0;

static int by_roll(const void *a, const void *b) {
    const Student *x = a, *y = b;
    return (x->roll > y->roll) - (x->roll < y->roll);
}

Student *find(int roll) {
    Student key = {roll};
    return bsearch(&key, list, n, sizeof(Student), by_roll);
}

int add(Student s) {
    if (find(s.roll) != NULL) return 0;   // roll already used
    if (n == cap) {
        int newcap = (cap == 0) ? 4 : cap * 2;
        Student *bigger = realloc(list, newcap * sizeof(Student));
        if (bigger == NULL) return 0;
        list = bigger;
        cap = newcap;
    }
    list[n++] = s;
    qsort(list, n, sizeof(Student), by_roll);   // keep it sorted
    return 1;
}

int delete_roll(int roll) {
    Student *p = find(roll);
    if (p == NULL) return 0;
    for (int i = p - list; i < n - 1; i++)
        list[i] = list[i + 1];   // everyone below moves up
    n--;
    return 1;
}

void list_all(void) {
    printf("%d students\n", n);
    for (int i = 0; i < n; i++)
        printf("  %d  %-12s %5.1f\n", list[i].roll, list[i].name, list[i].marks);
}

void report(void) {
    if (n == 0) { printf("No students yet\n"); return; }
    float sum = 0;
    int top = 0;
    for (int i = 0; i < n; i++) {
        sum += list[i].marks;
        if (list[i].marks > list[top].marks) top = i;
    }
    printf("Students: %d, average: %.2f\n", n, sum / n);
    printf("Topper: %s (%.1f)\n", list[top].name, list[top].marks);
}

int save(const char *file) {
    FILE *f = fopen(file, "wb");
    if (f == NULL) { perror(file); return 0; }
    fwrite(list, sizeof(Student), n, f);
    fclose(f);
    return 1;
}

int load(const char *file) {
    FILE *f = fopen(file, "rb");
    if (f == NULL) return 0;
    Student s;
    while (fread(&s, sizeof(Student), 1, f) == 1)
        add(s);
    fclose(f);
    return 1;
}
int count(void) {
    return n;
}

void free_all(void) {
    free(list);
    list = NULL;
    n = cap = 0;
}

main.c: only the menu.

#include <stdio.h>
#include "student.h"

int main() {
    if (load("students.dat")) printf("Loaded %d students\n", count());
    else printf("No saved file yet: starting empty\n");
    printf("1 add, 2 list, 3 search, 4 update, 5 delete, 6 report, 0 save+exit\n");
    int choice, roll;
    Student s, *p;
    do {
        printf("> ");
        if (scanf("%d", &choice) != 1) break;
        switch (choice) {
        case 1:
            if (scanf("%d %49[^\n] %f", &s.roll, s.name, &s.marks) == 3 && add(s))
                printf("Added %d\n", s.roll);
            else
                printf("Not added\n");
            break;
        case 2:
            list_all();
            break;
        case 3:
            scanf("%d", &roll);
            p = find(roll);
            if (p) printf("%d: %s, %.1f\n", p->roll, p->name, p->marks);
            else printf("Roll %d not found\n", roll);
            break;
        case 4:
            scanf("%d", &roll);
            p = find(roll);
            if (p && scanf("%f", &p->marks) == 1) printf("Updated %d\n", roll);
            else printf("Roll %d not found\n", roll);
            break;
        case 5:
            scanf("%d", &roll);
            if (delete_roll(roll)) printf("Deleted %d\n", roll);
            else printf("Roll %d not found\n", roll);
            break;
        case 6:
            report();
            break;
        case 0:
            if (save("students.dat")) printf("Saved %d students. Bye!\n", count());
            break;
        default:
            printf("No such option\n");
        }
    } while (choice != 0);
    free_all();
    return 0;
}

Compile and run (input from a file):

gcc main.c student.c -o records
./records < in.txt

With the same full-day input, the output is identical to the single-file version, and a second run starts with Loaded 2 students.

Why split? Each file has one job, the data is hidden behind functions, and you can change how records are stored (say, a linked list from episode 22) without touching main.c.

Common mistakes (and the real messages)

Mistake What you see Why Fix
101 students in int roll[100] No error: First: 101 0.0 (another student's data overwritten) C doesn't check array bounds a dynamic array that grows with realloc
scanf("%s", name) for "Aman Verma" No error: name Aman, marks 0.0 %s stops at a space scanf(" %49[^\n]", name)
fgets right after scanf("%d") No error: empty name the leftover '\n' is read as a line leading space in " %49[^\n]", or clear the line first
scanf(" %[^\n]", name) with char name[20] and a long name *** stack smashing detected ***: terminated no width: buffer overflow char name[50] and " %49[^\n]"
scanf("%d", roll) (no &) warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Wformat=], then Segmentation fault scanf needs the variable's address scanf("%d", &roll)
Missing break; after case 1 No error: Added 105 and then the whole list prints falls through into case 2 end every case with break;
int remove(int roll) error: conflicting types for 'remove'; have 'int(int)' stdio.h already declares remove() (it deletes a file) a unique name: delete_roll
bsearch on an array that add never sorted No error: Roll 105 not found binary search needs sorted data qsort after every add, same comparator
list = realloc(list, ...) No error, until memory runs out: the old block leaks on failure realloc returns NULL and you lose the only pointer Student *bigger = realloc(...), check, then assign
Keeping p = find(...) across an add Wrong student or a crash realloc may move the array, qsort reorders it call find again

Mini project: extend it

Ideas to make the system your own:

  • Search by name (case-insensitive), or show every student whose name contains some text (strstr).
  • Text file storage with fprintf / fscanf, so the office can open the file in any editor.
  • Grades in the report: A (90+), B (75+), C (60+), D (40+), F.
  • Undo the last delete.
  • Sort the list by marks (highest first) for a rank list, without breaking the roll order that bsearch needs (sort a copy).
  • Pass/fail count and the lowest marks in the report.
  • Input checks: reject marks outside 0 to 100 and roll numbers ≤ 0.
  • Replace the array with a linked list (episode 22) or a BST (episode 24) by changing only student.c.

Practice

  1. Search a student by name with strcmp.
  2. Save and load the students as a text file with fprintf / fscanf (names with spaces!).
  3. Add a grade (A to F) to each line of the list.
  4. Undo the last delete.
Solutions

All four, verified together (a fixed array of 10 keeps the example short; in the real system use the dynamic array):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int roll;
    char name[50];
    float marks;
} Student;

Student list[10] = {{101, "Aman Verma", 72}, {103, "Kabir Singh", 64}, {105, "Zoya Ahmed", 91}};
int n = 3;
Student last_deleted;          // for undo
int can_undo = 0;

// 1. search by name: a linear search with strcmp
Student *find_name(const char *name) {
    for (int i = 0; i < n; i++)
        if (strcmp(list[i].name, name) == 0) return &list[i];
    return NULL;
}

// 2. save and load as a text file: one student per line, name last
void save_text(const char *file) {
    FILE *f = fopen(file, "w");
    if (f == NULL) { perror(file); return; }
    for (int i = 0; i < n; i++)
        fprintf(f, "%d %.1f %s\n", list[i].roll, list[i].marks, list[i].name);
    fclose(f);
}

int load_text(const char *file, Student out[], int max) {
    FILE *f = fopen(file, "r");
    if (f == NULL) return 0;
    int k = 0;
    while (k < max && fscanf(f, "%d %f %49[^\n]", &out[k].roll, &out[k].marks, out[k].name) == 3)
        k++;
    fclose(f);
    return k;
}

// 3. a grade for the report
char grade(float m) {
    if (m >= 90) return 'A';
    if (m >= 75) return 'B';
    if (m >= 60) return 'C';
    if (m >= 40) return 'D';
    return 'F';
}

// 4. delete with undo: remember the last deleted student and its place
int delete_at(int i) {
    last_deleted = list[i];
    can_undo = 1;
    for (; i < n - 1; i++) list[i] = list[i + 1];
    n--;
    return 1;
}

void undo(void) {
    if (!can_undo) return;
    int i = n;                                   // insert back in roll order
    while (i > 0 && list[i - 1].roll > last_deleted.roll) {
        list[i] = list[i - 1];
        i--;
    }
    list[i] = last_deleted;
    n++;
    can_undo = 0;
}

int main() {
    Student *p = find_name("Zoya Ahmed");
    if (p) printf("Found by name: %d %s\n", p->roll, p->name);

    save_text("students.txt");
    Student back[10];
    int k = load_text("students.txt", back, 10);
    printf("Loaded %d from text, first: %d %s %.1f\n", k, back[0].roll, back[0].name, back[0].marks);

    for (int i = 0; i < n; i++)
        printf("%d %-12s %5.1f  %c\n", list[i].roll, list[i].name, list[i].marks, grade(list[i].marks));

    delete_at(0);
    printf("After delete: %d students, first is %d\n", n, list[0].roll);
    undo();
    printf("After undo: %d students, first is %d %s\n", n, list[0].roll, list[0].name);
    return 0;
}
Found by name: 105 Zoya Ahmed
Loaded 3 from text, first: 101 Aman Verma 72.0
101 Aman Verma    72.0  C
103 Kabir Singh   64.0  C
105 Zoya Ahmed    91.0  A
After delete: 2 students, first is 103
After undo: 3 students, first is 101 Aman Verma

students.txt after save_text:

101 72.0 Aman Verma
103 64.0 Kabir Singh
105 91.0 Zoya Ahmed
  • 1. A linear search is fine for names: the array is sorted by roll, not by name, so bsearch can't be used unless you sort a copy by name.
  • 2. Write the name last on each line, so fscanf(f, "%d %f %49[^\n]", ...) can read a name with spaces up to the end of the line.
  • 4. Remember the deleted student; to undo, shift the bigger rolls one place right and put it back, so the array stays sorted.

Quick quiz

int n = 0, cap = 0;
// add(): when n == cap,
//   newcap = (cap == 0) ? 4 : cap * 2;

// after adding 100 students,
// what is cap?
  • A. 100
  • B. 104
  • C. 128
  • D. 200
Answer

C: 128. 4 → 8 → 16 → 32 → 64; the 65th student finds 64 slots full and doubles it to 128, which holds all 100. 28 slots sit empty: the price of doubling.

More quick checks:

  1. Why does scanf(" %49[^\n]", name) start with a space?
    AnswerTo skip whitespace, including the newline left behind by an earlier scanf("%d").
  2. Why does fread go in a while loop condition?
    AnswerIt returns how many records it read; at the end of the file it returns 0 and the loop stops.
  3. After delete_roll, is the array still sorted?
    AnswerYes: everyone after the deleted student moves up one place, keeping their order.

Interview questions

  • How does a dynamic array grow? Why double the capacity instead of adding a fixed amount? What is the amortised cost of adding?
  • Why is p = realloc(p, size) dangerous? Write the safe version.
  • What's the difference between fwrite/fread (binary) and fprintf/fscanf (text) files? When would you choose each?
  • Why does fgets after scanf("%d") read an empty line? Give two ways to fix it.
  • How do you read a full name with spaces safely using scanf? Why the width?
  • What is a buffer overflow? How does -fstack-protector detect it?
  • What happens if you forget break in a switch case? When is fall-through useful?
  • Why must the array be sorted for bsearch? What does bsearch return if the key is missing?
  • How do you delete an element from the middle of an array? What is its time complexity?
  • Why can a pointer returned by find become invalid after an insert?
  • How would you split this program into a header and source files? What does static on a global do?
  • What is an include guard, and why is it needed?

Glossary

Term Meaning Example
Record All the facts about one thing, kept together roll 101, "Aman Verma", 72
Record system A program that adds, lists, searches, updates and deletes records today's student register
struct A type that groups several values into one variable typedef struct { int roll; ... } Student;
typedef Gives a type a short name Student instead of struct student
Dynamic array An array on the heap that can grow while the program runs list, n, cap
Capacity (cap) How many slots are rented; n is how many are used n = 1000, cap = 1024
Capacity doubling When full, grow to twice the size 4 → 8 → 16 → …
Amortised O(1) Cheap on average, even if an occasional add is expensive adding to a doubling array
realloc Resize a heap block, keeping its contents (it may move) realloc(list, newcap * sizeof(Student))
Memory leak Heap memory that is never freed and can't be reached list = realloc(list, ...) failing
RAM The computer's working memory; wiped when a program ends every variable
Binary file A file holding raw bytes, exactly as in memory students.dat
fwrite / fread Write / read whole items to / from a file fwrite(list, sizeof(Student), n, f)
"wb" / "rb" Open a file to write / read in binary mode fopen("students.dat", "wb")
perror Prints your text plus the system's reason for the last error students.dat: Permission denied
Newline character '\n', the Enter key stored in the input left behind by scanf("%d")
Leftover newline The '\n' that scanf didn't read, waiting for the next read fgets returns an empty line
Scanset %[...] in scanf: read only these characters (or, with ^, all except these) %[^\n] = everything except a newline
Width Maximum characters scanf stores for %s or %[ %49[^\n]
Buffer overflow Writing past the end of an array a 29-character name into char name[20]
Stack smashing gcc's message when a function's stack area was overwritten *** stack smashing detected ***
Menu loop A loop that shows choices and runs one job each time, until exit do { ... switch ... } while (choice != 0);
Fall-through A case without break continues into the next case missing break after case 1
bsearch Library binary search; needs sorted data, returns a pointer or NULL find(roll)
qsort Library sort with a comparator qsort(list, n, sizeof(Student), by_roll)
Comparator Function that returns negative, zero or positive for two items by_roll
Stale pointer A pointer into memory that has moved or changed p kept across add
Shift down (delete) Move every later item one place up to close the gap list[i] = list[i + 1]
Header file A .h file with declarations shared between .c files student.h
Include guard #ifndef / #define / #endif so a header is included once STUDENT_H
static global A global visible only inside its own .c file static int n

Summary

  • The obvious program (fixed arrays, variables only) overflows silently at student 101 and forgets everything when it ends.
  • One record = one struct; store them in a dynamic array (list, n, cap) that doubles with realloc, through a temporary pointer.
  • fwrite saves the whole array in one call, fread loads it back one record at a time; a missing file just means the first day.
  • Read names with scanf(" %49[^\n]", name) and char name[50]: the space skips the leftover newline, the scanset reads the whole line, the width prevents overflow.
  • A menu loop is a do while around a switch; end every case with break, and stop if scanf fails.
  • bsearch needs sorted data: qsort after every add, with the same comparator. Delete by shifting down; update through the pointer from find, and don't keep that pointer across an add.
  • The report handles zero students, then prints the average and the topper.
  • Split real projects into student.h, student.c (with static data) and main.c.

Next episode: C interview questions: pointers, memory, strings, and the tricky outputs interviewers love.