Starter lesson
Read a line without overflowing a buffer
Low-level programs often receive input from files, devices, or users. A fixed-size buffer is safe only when the program limits how much it reads and checks the result.
#include <stdio.h>
#include <string.h>
int main(void) {
char name[32];
if (fgets(name, sizeof name, stdin) == NULL) {
return 1;
}
name[strcspn(name, "\n")] = '\0';
printf("Hello, %s\n", name);
return 0;
}
What to expect
The program reads at most 31 input characters plus the string terminator, then removes a trailing newline when present.
Key idea: In C, pass the buffer size to input functions and handle failure before using the data.