Skip to the task
Layout
Back to classic view

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

READTask 10 of 20 · step 5: Common mistakesCommon mistakes
Common mistakes in practice/11/

An unchecked malloc, p = realloc(p, ...), malloc(n) without sizeof, a forgotten '\0', a leak, use after free, two frees, old pointers after realloc, sizeof p.

Details & hint

Memory errors are most dangerous because under MinGW the program often "works". GitHub CI with ASan catches them.

Common mistakes
  • An unchecked malloc/realloc. On NULL, p[0] = 1 writes into nowhere. After every one – if (p == NULL).
  • p = realloc(p, ...). On NULL the old block is lost and can never be freed. Into a temporary pointer first.
  • malloc(n) instead of malloc(n * sizeof *p). 10 int is 40 bytes, not 10. ASan: heap-buffer-overflow.
  • A forgotten '\0'. A copy of a string needs strlen(s) + 1 bytes.
  • Memory never freed. LeakSanitizer: detected memory leaks. Especially on an early return after an error: group_free is needed there too.
  • Use after free. The pointer still holds the address, but the block isn't yours. ASan: heap-use-after-free; when the free and the use are in the same function, CI's GCC already stops at compile time: pointer ‘p’ used after ‘free’. After free – p = NULL.
  • free twice. ASan: attempting double-free (when the two free calls are in different functions; in the same function CI's GCC refuses to compile it: used after ‘free’). p = NULL after free protects here too: free(NULL) does nothing.
  • free on something malloc didn't give. free(&x) or free(p + 1) – undefined behaviour.
  • Old pointers after realloc. int *first = &m.data[0]; and then array_add – after a move, first points at freed memory.
  • sizeof p instead of the capacity. A pointer is 8 bytes, however many elements are behind it. Keep the count yourself (count, capacity).
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;
}