Using deprecated functions like gets() or unbounded scanf("%s") to accept user input in C is a primary source of stack buffer overflow vulnerabilities. Secure C software requires bounded input handling using fgets().
Secure Input Reading with fgets()
#include <stdio.h>
#include <string.h>
#define MAX_BUFFER 64
int main(void) {
char username[MAX_BUFFER];
printf("Enter username: ");
// Safely read up to 63 chars + '\0' null terminator from stdin
if (fgets(username, sizeof(username), stdin) != NULL) {
// Strip trailing newline character '\n' added by fgets
username[strcspn(username, "\n")] = '\0';
printf("Welcome, %s! (Length: %zu)\n", username, strlen(username));
}
return 0;
}
Comments and corrections