gets() in C

Last Updated : 14 Jan, 2025

In C, gets() is a function used to read a line of input from standard input (stdin) into a character array. However, gets() has been deprecated since C11 and removed in later standards due to its unsafe behaviour, such as not limiting the number of characters read, which can lead to buffer overflows.

Let's take a look at an example:

C
#include <stdio.h>

int main() {
    char buff[100];
    printf("Enter a string: ");
  
  	// Taking input using gets()
    gets(buff);
    printf("You entered: %s", buff);
    return 0;
}


Output

Enter a string: Geeksforgeeks (entered by the user)You entered: Geeksforgeeks

Explanation: In this program, gets() reads a line of input from the user and stores it in the array buff.

Syntax of gets()

gets() is defined in the <stdio.h> header file.

gets(buff);

Parameters:

  • buff: A pointer to the character array where the input string will be stored.

Return Value:

  • Returns a pointer to the string (str) on success.
  • Returns NULL if an error occurs or if EOF is encountered before any characters are read.

Why gets() is Unsafe?

The gets() is unsafe due to following reasons:

  • Lack of Buffer Size Control: gets() does not provide a way to limit the number of characters read, leading to potential buffer overflows if the input exceeds the allocated array size.
  • No Error Handling: Unlike fgets(), gets() does not provide reliable mechanisms to handle errors or EOF effectively.
  • Deprecated and Removed: Starting from the C11 standard, gets() has been deprecated and eventually removed from the standard library due to its inherent risks.

Examples of gets()

The following examples demonstrate the use of gets() function in C:

Buffer Overflow with gets()

C
#include <stdio.h>

int main() {
  
  	// Small buffer size
    char buff[10];
    printf("Enter a string: ");
  
  	// No size limitation on input
    gets(buff);
    printf("You entered: %s\n", buff);
    return 0;
}


Output

Enter a string: This is a larger string (entered by the user)You entered: This is a larger string

Explanation: This input exceeds the buffer size (10), potentially causing a buffer overflow, leading to undefined behavior or program crashes.

Key Differences Between gets() and fgets()

The following table lists the primary differences between gets() and fgets() function in C:

Aspectgets()fgets()
Buffer Size ControlNo size control; prone to buffer overflow.Allows specifying the maximum size; safe.
Newline HandlingDiscards the newline character.Retains the newline character.
Error HandlingLimited error handling capabilities.Returns NULL on error or EOF.
StatusDeprecated in C11 and later.Recommended for modern use.
Comment