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
C Pointers
C Pointer Arithmetic
C Pointer to Pointer
C Pointers and Arrays
C Pointers and Functions
C Dynamic Memory Allocation
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is a pointer in C?
What is a NULL pointer in C?
What is the difference between malloc() and calloc() in C?
What is a memory leak in C and how to avoid it?
What is a dangling pointer in C?
What is the difference between an array and a pointer in C?
What is a void pointer in C?