Skip to the task
Layout
Back to classic view

You are looking ahead. Your place is still task 1: malloc.

HOMEWORKTask 19 of 20 · step 8: Homework: a group with no limitHomework: a group with no limit
Homework: a group with no limit in practice/11/

hw/12-gradebook: Group with realloc, group_load and group_save without MAX_STUDENTS; main frees the group on every path.

Checklist

  • Every task is one commit with a clear message.
  • Zero compiler warnings: the code builds with -Werror.
  • Once per topic you step through your code in the debugger (CLion, gdb).
  • Every function has preconditions and postconditions, and assert tests check them.
  • A multi-file program: .h files with Doxygen comments and their own CMake target.
  • Input only through the safe functions of your own input.h.
  • Every error code is checked (fopen, fclose, malloc and so on).
  • CI is clean: no AddressSanitizer or UBSan reports.
Details & hint

The gradebook, version 6: the MAX_STUDENTS limit is gone. Students live in a dynamic array that grows with realloc, and all the memory is freed.

The task: hw/12-gradebook

input.h, input.c – put your own from hw/11-gradebook here.

gradebook.h – replace the first part with yours from hw/11-gradebook. The new part is written: Group and six functions with contracts.

typedef struct {
    Student *s;   /**< the students, or NULL while the group is empty */
    int n;        /**< how many students */
    int capacity; /**< how many fit in s before realloc is needed */
} Group;

gradebook.c – copy your functions from hw/11-gradebook and write the new ones:

function what it does
group_init(g) an empty group: NULL, 0, 0
group_add(g, s) a copy of the student at the end; when n == capacity, the capacity becomes 4, 8, 16... via realloc and a temporary pointer; 0 if no memory was given
group_free(g) free and an empty group again
parse_student(line, s) one file line into a student – the same checks as load_students; pull them out of load_students into a function of their own
group_load(path, g, &line_no) like load_students, only without max: as many lines, as many students. GB_TOO_MANY now means "out of memory"
group_save(path, g) like save_students, only for the whole group

Also: find_student, sort_by_name, best_student no longer have the precondition n <= MAX_STUDENTS – remove that assert, otherwise a group of 25 stops.

main.c – as in homework 11, only with Group:

Students loaded from gradebook.txt: 11
How many new students? 101
New students must be between 0 and 100.
How many new students? 1
Student 1 of 1
Full name: Zita Zitiene
...
Best average: Lina Linaite (10.00)
Students saved to gradebook.txt: 12
  • No file – No gradebook.txt yet: starting an empty gradebook.
  • Any other error – Error: gradebook.txt, line 3: bad line format., The gradebook is unchanged., group_free and EXIT_FAILURE. What was read before the error has to be freed too.
  • New students – from 0 to 100 (New students must be between 0 and 100.). There is no "The gradebook is full." any more.
  • group_add returned 0 – Out of memory., free and EXIT_FAILURE.
  • Before every return – group_free. No MAX_STUDENTS is left in main.c.

Tests

ctest --preset debug -L hw12
  • hw12_functions – unit_tests.c: 25 students (the capacity must be 32), sorting, search, the best one, save and load, parse_student with good and bad lines, no file. While the functions are empty:

    Assertion failed: nearly_equal(average(grades, 5), 8.8), file .../hw/12-gradebook/unit_tests.c, line 29
    
  • hw12_precondition – group_add(NULL, ...) must stop at your assert.

  • hw12_gradebook_1–3 – the whole program: no file; 11 students plus one more (12 in all – more than the old limit of 10); a broken line 3 (gradebook.txt must stay unchanged).

  • hw12_input, hw12_doxygen, hw12_memory, hw12_main – input.c is yours; gradebook.h has Doxygen and Group; gradebook.c uses assert(, realloc(, free(, fclose( and doesn't use fscanf( or while (!feof(; main.c uses Group, group_load(, group_save(, group_free( and has no MAX_STUDENTS; no TODO anywhere.

GitHub CI runs the same tests with ASan and LeakSanitizer: a group never freed or a write past a block fails a test there, even if everything passes on MinGW.

Handing in

Commit and push. Actions → Points: HW 12 (Gradebook in dynamic memory), 10 points when all 9 tests pass.

practice 11 measurements.c Code Diff
UNCHANGED This step does not change this file.
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_MEASUREMENTS 100
typedef enum { OK = 0, CANNOT_OPEN, BAD_LINE, TOO_MANY, WRITE_FAILED } Error;
/* A description of the error code for a person. */
const char *error_text(Error e) {
switch (e) {
case OK:
return "ok";
case CANNOT_OPEN:
return "cannot open the file";
case BAD_LINE:
return "not a number";
case TOO_MANY:
return "too many measurements";
case WRITE_FAILED:
return "write failed";
}
return "unknown error";
}
/* Prints how the work with the file path ended. */
void print_error(const char *path, Error e, int line_no) {
if (e == BAD_LINE) {
printf("%s, line %d: %s\n", path, line_no, error_text(e));
} else {
printf("%s: %s\n", path, error_text(e));
}
}
/* Reads one number per line into t[0..max-1].
Before: path, t, count, line_no != NULL, max > 0.
After: OK and *count numbers; otherwise an error code,
and *line_no is the number of the line it stopped at. */
Error read_measurements(const char *path, double t[], int max, int *count, int *line_no) {
assert(path != NULL && t != NULL && count != NULL && line_no != NULL);
assert(max > 0);
*count = 0;
*line_no = 0;
FILE *f = fopen(path, "r");
if (f == NULL) {
return CANNOT_OPEN;
}
Error result = OK;
char line[64];
while (fgets(line, sizeof line, f) != NULL) {
(*line_no)++;
char *end;
double x = strtod(line, &end);
while (isspace((unsigned char)*end)) {
end++;
}
if (end == line || *end != '\0') {
result = BAD_LINE;
break;
}
if (*count == max) {
result = TOO_MANY;
break;
}
t[*count] = x;
(*count)++;
}
fclose(f);
return result;
}
/* Writes the report to the file path.
Before: path != NULL, count >= 0. */
Error write_report(const char *path, int count, double average) {
assert(path != NULL && count >= 0);
FILE *out = fopen(path, "w");
if (out == NULL) {
return CANNOT_OPEN;
}
int a = fprintf(out, "Measurements: %d\n", count);
int b = fprintf(out, "Average: %.2f\n", average);
if (fclose(out) != 0 || a < 0 || b < 0) {
return WRITE_FAILED;
}
return OK;
}
int main(void) {
const char *path = "measurements.txt";
double t[MAX_MEASUREMENTS];
int count;
int line_no;
Error e = read_measurements(path, t, MAX_MEASUREMENTS, &count, &line_no);
if (e != OK) {
print_error(path, e, line_no);
return EXIT_FAILURE;
}
double sum = 0.0;
for (int i = 0; i < count; i++) {
sum += t[i];
}
double average = count > 0 ? sum / count : 0.0;
printf("Measurements read: %d\n", count);
printf("Average: %.2f\n", average);
const char *report = "report.txt";
e = write_report(report, count, average);
if (e != OK) {
print_error(report, e, 0);
return EXIT_FAILURE;
}
printf("Report written: %s\n", report);
const char *others[] = {"bad.txt", "missing.txt"};
for (int i = 0; i < 2; i++) {
e = read_measurements(others[i], t, MAX_MEASUREMENTS, &count, &line_no);
print_error(others[i], e, line_no);
}
return EXIT_SUCCESS;
}