A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
gets reads a line from stdin into a buffer with no length limit. There is no parameter for the buffer size. If the input is longer than the buffer, gets writes past the end. There is no way to use gets safely. Not with careful input validation. Not with a large buffer. Not with anything. The function is fundamentally broken. It was deprecated in C99, removed from the C11 standard, and has been the root cause of more security vulnerabilities than any other single function in the C library.
#include <stdio.h>int main(void) {char buffer[16];printf("Enter text: ");gets(buffer);printf("You entered: %s\n", buffer);return 0;}
41 bytes written into a 16-byte buffer. The overflow overwrites the return address, the saved frame pointer, and adjacent stack frames. In 1988, the Morris Worm exploited exactly this pattern in the Unix fingerd daemon. In 2014, CVEs were still being assigned for gets-based overflows in shipped software. The function has no safe use case.
#include <stdio.h>#include <string.h>int main(void) {char buffer[16];printf("Enter text: ");if (fgets(buffer, sizeof(buffer), stdin) == NULL) {printf("No input.\n");return 1;}buffer[strcspn(buffer, "\n")] = '\0';printf("You entered: \"%s\"\n", buffer);return 0;}
fgets reads at most sizeof(buffer) - 1 characters, leaving room for the null terminator. The excess input remains in the stream. No overflow. No crash. No vulnerability. The input is truncated to 15 characters, which is the correct behavior for a 16-byte buffer. If you need the full line, use a larger buffer or read in chunks.
If you see gets in a codebase, replace it with fgets immediately. Not in the next sprint. Not after the refactor. Now. It is a vulnerability with a one-line fix. The C standard committee removed it for a reason. Listen to them. Next: nested functions, a GCC extension that standard C does not support.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.