Skip to the task
Layout
Back to classic view

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

READTask 7 of 20 · step 4: Safe inputSafe input
Safe input in practice/06/

Why not scanf("%s") and gets, the three fgets outcomes, strtol with the end pointer and errno, fflush and INPUT_ECHO.

Details & hint

Since topic 2 you've read numbers and lines with read_int, read_double and read_line from the course's input.h. Now you see how they work inside, and in step 5 you write the same kind of thing yourself.

Why not scanf

char name[8];
scanf("%s", name);

scanf("%s") doesn't know the array's size. Type "Konstantinas" and it writes 13 bytes into an 8-byte array, wrecking the neighbouring variables. The compiler gives no warning, and the program often doesn't even crash – the bug shows up later and somewhere else. GitHub CI with AddressSanitizer stops such a program with stack-buffer-overflow.

On top of that, scanf("%d") given abc reads nothing and leaves abc in the input: the next scanf refuses it again, and the program loops forever.

gets(t) is even worse: no size at all. It was removed from C in the C11 standard. MinGW still lets it through, but on Linux (CI) with -std=c17 a program with gets doesn't build.

fgets: a line that fits

char t[8];
if (fgets(t, sizeof t, stdin) == NULL) {
    /* the input ended */
}

fgets reads at most sizeof t - 1 bytes, stops after '\n' and always adds '\0'. What happens with char t[8]:

typed t after fgets what's left in the input
Ona ↵ "Ona\n" nothing
Konstantinas ↵ "Konstan" tinas ↵
(end of file) unchanged, returns NULL —

Hence three jobs after every fgets:

  1. NULL – the input ended: there's nothing left to ask.
  2. No '\n' at the end – the line is too long. The rest must be thrown away up to '\n' (getchar in a loop), or the next fgets reads it.
  3. A '\n' at the end – cut it off: t[strcspn(t, "\r\n")] = '\0';. \r comes from Windows files read on Linux.

strtol: text to a number

char *end;
errno = 0;
long x = strtol(t, &end, 10);

strtol skips spaces at the start, reads digits, and writes into end where it stopped. Through a pointer – topic 8: the function returns two results. They decide whether the text fits:

t x end points to fits?
"42" 42 '\0' yes
"abc" 0 the start of t no: not a single digit
"12abc" 12 "abc" no: garbage at the end
"99999999999" — '\0' no: doesn't fit in int

The last row goes two ways. On Windows long is 4 bytes and strtol reports errno == ERANGE. On Linux long is 8 bytes: the number fits in a long but not in an int. So both are checked: errno == ERANGE and x < INT_MIN || x > INT_MAX (<limits.h>).

strtod is the same for real numbers. "7,5" stops at the comma, so it doesn't fit; "1e999" is too big – errno == ERANGE.

The prompt and fflush

printf("> "); without '\n' may stay in a buffer: when the program doesn't run in a terminal (the CLion console, the tests), output is collected and written out later. fflush(stdout); after the prompt shows it at once.

INPUT_ECHO: how the tests see the input

When you type, the console shows what you type. The tests give the input from a file, and it doesn't show in the output. So the course's input.h, when the environment variable INPUT_ECHO equals 1, prints each line it reads itself:

const char *e = getenv("INPUT_ECHO");
if (e != NULL && strcmp(e, "1") == 0) {
    printf("%s\n", t);
}

That way a test's expected output looks exactly like the console. Your module does the same – without it the tests can't make sense of your program.

practice 06 main.c Code Diff
UNCHANGED This step does not change this file.
#include <assert.h>
#include <stdio.h>
#include "input.h"
#define DAYS 7
/* Reads n temperatures into the array t.
Before: 1 <= n <= DAYS.
After: t[0]..t[n - 1] are filled. */
void read_temperatures(int t[], int n) {
assert(n >= 1 && n <= DAYS);
for (int i = 0; i < n; i++) {
printf("%d. ", i + 1);
t[i] = read_int("Temperature: ");
}
}
/* Prints n values of the array on one line, separated by a space.
Before: 0 <= n <= DAYS. */
void print_array(const int t[], int n) {
assert(n >= 0 && n <= DAYS);
for (int i = 0; i < n; i++) {
if (i > 0) {
printf(" ");
}
printf("%d", t[i]);
}
printf("\n");
}
/* The arithmetic mean.
Before: 1 <= n <= DAYS.
After: (t[0] + ... + t[n - 1]) / n. */
double average(const int t[], int n) {
assert(n >= 1 && n <= DAYS);
int sum = 0;
for (int i = 0; i < n; i++) {
sum += t[i];
}
return (double)sum / n;
}
/* The index of the warmest day (the first one, if several are equal).
Before: 1 <= n <= DAYS.
After: t[i] >= t[j] for every j. */
int warmest(const int t[], int n) {
assert(n >= 1 && n <= DAYS);
int best = 0;
for (int i = 1; i < n; i++) {
if (t[i] > t[best]) {
best = i;
}
}
return best;
}
/* Linear search: the index of the first such value.
Before: 0 <= n <= DAYS.
After: i such that t[i] == value, or -1 if there is none. */
int find(const int t[], int n, int value) {
assert(n >= 0 && n <= DAYS);
for (int i = 0; i < n; i++) {
if (t[i] == value) {
return i;
}
}
return -1;
}
/* Sorts in ascending order, by selection.
Before: 0 <= n <= DAYS.
After: t[0] <= t[1] <= ... <= t[n - 1]. */
void sort_array(int t[], int n) {
assert(n >= 0 && n <= DAYS);
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (t[j] < t[min]) {
min = j;
}
}
int temp = t[i];
t[i] = t[min];
t[min] = temp;
}
}
int main(void) {
int temperatures[DAYS];
read_temperatures(temperatures, DAYS);
printf("Temperatures: ");
print_array(temperatures, DAYS);
printf("Average: %.2f\n", average(temperatures, DAYS));
int w = warmest(temperatures, DAYS);
printf("Warmest: day %d, %d C\n", w + 1, temperatures[w]);
int sorted[DAYS];
for (int i = 0; i < DAYS; i++) {
sorted[i] = temperatures[i];
}
sort_array(sorted, DAYS);
printf("Sorted: ");
print_array(sorted, DAYS);
printf("Median: %d C\n", sorted[DAYS / 2]);
int target = read_int("Which temperature to look for? ");
int pos = find(temperatures, DAYS, target);
if (pos == -1) {
printf("%d C was not on any day.\n", target);
} else {
printf("%d C was first on day %d.\n", target, pos + 1);
}
return 0;
}