Why should we not use the gets() function in C?

gets() reads a line but has no way to know the size of the array. If the user types more characters than the array can hold, the extra characters are written outside the array. This is a buffer overflow, and attackers can use it. The function was removed from the C11 standard.

#include <stdio.h>

int main(void) {
    char name[10];

    fgets(name, sizeof(name), stdin);   // reads at most 9 characters
    printf("%s", name);
    return 0;
}

fgets() takes the size, so it is safe. Note that it keeps the new line character. See String Input and Output.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.