Summarise With AI
Back

Gets() in C: A Complete Guide

16 Jan 2026
5 min read

What This Blog Covers

  • Explains gets() in C, its syntax, behavior, and how it reads input into character arrays.
  • Shows how gets() works internally, including newline handling and return values.
  • Demonstrates practical examples of using gets() with strings and sentences.
  • Clearly explains why gets() is unsafe, with buffer overflow examples.
  • Compares gets() with safer alternatives like fgets(), gets_s(), and getline().
  • Helps students understand modern best practices for secure input handling in C.

Introduction

The gets() in C function was once a simple way to read user input, but it is now one of the most dangerous functions ever included in the C standard library.

Many beginners still encounter gets() in old textbooks, legacy code, or exam questions without understanding why it is unsafe. If you use gets() not realizing its danger, it can cause buffer overflow, system crashes, and even security holes of serious nature.

Here, you will learn how gets() in C works, why it was deprecated and removed, real examples of its behavior, and which safer alternatives you should use instead to write secure and modern C programs.

Introduction to gets()

The Gets() in C function is part of the C standard library and is declared in the <stdio.h> header file. Its main function is to receive a line of text from the standard input (often the keyboard) and save it in an array of characters (string) that the programmer has supplied.

Syntax

char *gets(char *str);

Where str is a pointer for the character array that will hold the input string. The array should be large enough to hold the input and the null terminator.

Parameters and Function Signature of gets()

The gets() function in C is defined with the following signature:

char gets(char str);

Parameter:

  • str: This is the only parameter accepted by gets(). It must be a pointer to a character array (also known as a string in C) where the input from the user will be stored.
    • The character array should be large enough to hold all the characters entered by the user, plus the null terminator ('\0') that marks the end of the string in C.
    • If the buffer is too small for the input, extra characters will overwrite adjacent memory, leading to undefined behavior.

Return Value:

  • On success, gets() returns the same pointer (str) that was passed as the argument. This allows the returned value to be used directly in expressions or chained function calls.
  • If an error occurs or the end-of-file (EOF) is encountered before any characters are read, gets() returns NULL.

How gets() is Called:

To use gets(), declare a character array and pass its name (which acts as a pointer to its first element) to the function. For example:

char buffer[100]; 
gets(buffer);

In this example:

  • buffer is a character array with space for 100 characters.
  • gets(buffer) reads a line of input from standard input and stores it in buffer.

Summary Table:

Aspect Type Description
Parameter (str) char * Pointer to the character array where the input string is stored.
Return Value char * Returns str on success; returns NULL on error or when EOF is encountered.

Important Note:

Make sure that the character array supplied to gets() is always big enough to accommodate the null terminator and the expected input. Buffer overflows and unsteady program behavior may result from failing to accomplish this.

Functionality and Behavior

A line of text can be received from standard input (often the keyboard) and stored in a character array supplied by the programmer using gets() in C function.

How gets() Works

  • The function reads input character by character from standard input.
  • It continues reading until it encounters:
    • a newline character ('\n'), or
    • an end-of-file (EOF) condition.
  • When a newline character is encountered:
    • the newline is not stored in the buffer,
    • it is replaced with a null terminator ('\0'), marking the end of the string.

This behavior ensures that the input is stored as a properly null-terminated C string, which can be safely used with standard string-handling functions.

Return Value Behavior

  • On successful input, gets() returns the same pointer that was passed to it.
  • If an input error occurs or EOF is encountered before any characters are read, the function returns NULL.

Critical Limitation

  • The gets() function does not perform boundary checking.
  • It does not verify whether the destination buffer is large enough to hold the input.
  • If the user enters more characters than the buffer can store, the function continues writing beyond allocated memory.

Impact of This Limitation

  • Causes buffer overflow.
  • Can lead to program crashes, memory corruption, or security vulnerabilities.
  • This design flaw is the primary reason why gets() was deprecated and removed from modern C standards.

Note 

The gets() function reads input until a newline or EOF and stores it as a null-terminated string, but it performs no bounds checking. This makes it unsafe, as excessive input can cause buffer overflows and security vulnerabilities.

Examples of Usage

The gets() function was traditionally used in C programs to read a line of text from the user and store it in a character array. Below are practical examples demonstrating how gets() can be used in C code.

Example 1: Reading and Displaying a String

This basic program asks the user to enter a string, uses gets() to read the input, and then shows the string that was entered.

#include <stdio.h>

int main() {
    char str[100];

    printf("Enter a string: ");
    gets(str);  // Read input from the user

    printf("You entered: %s\n", str);  // Display the input

    return 0;
}

Output:

Enter a string: Hello, World! 
You entered: Hello, World!

Explanation:

  • char str[100]; declares a character array to hold the input.
  • gets(str); reads a line of text from standard input and stores it in str.
  • printf("You entered: %s\n", str); prints the string entered by the user.

Example 2: Reading Multiple Words

Gets() reads the full line, including spaces, until the user hits Enter, in contrast to methods like scanf ("%s", str), which stop reading input at the first whitespace.

#include <stdio.h>

int main() {
    char sentence[200];

    printf("Enter a sentence: ");
    gets(sentence);   // Reads the whole line, including spaces

    printf("Your sentence: %s\n", sentence);

    return 0;
}

Output:

Enter a sentence: C programming is fun! 
Your sentence: C programming is fun!

Explanation:

  • The user can write sentences with spaces since gets() catches the complete line.

Example 3: Demonstrating Input Length

You can use gets() to read strings of varying lengths, as long as the buffer is large enough to store the input and the null terminator.

#include <stdio.h>

int main() {
    char name[50];

    printf("Enter your full name: ");
    gets(name);

    printf("Hello, %s!\n", name);

    return 0;
}

Output:

Enter your full name: Ada Lovelace 
Hello, Ada Lovelace!

Explanation:

  • The buffer name is sized to accommodate typical full names, and gets() reads the entire input until Enter is pressed.

Note:

When using gets(), always ensure the character array is large enough to hold the expected input and the null terminator ('\0'). This prevents overwriting memory beyond the buffer (see the security section for more details).

Limitations and Security Risks of gets()

Once a popular method for reading strings from input, the C Gets() function is today regarded as extremely dangerous because of its basic design problems. It was formally eliminated in C11 after being deprecated in the C99 standard.

1. Lack of Bounds Checking

The most critical issue with gets() is its complete lack of bounds checking. Regardless of how much buffer space is available, gets() reads input until it comes across a newline or end-of-file when you provide it a character array. This implies that if a user inputs more characters than the buffer can accommodate, the extra characters are nevertheless written to memory, causing the buffer to overflow. 

Gets() in C offers no such protection, in contrast to safer alternatives like fgets(), which let the programmer set the maximum amount of characters to read. Because of this, the function is naturally risky, particularly when input is uncertain or controlled by the user.

2. Buffer Overflow Example

For an example of the risk, have a look at this simple program:

#include <stdio.h>

int main() {
    char str[10];
    printf("Enter a string: ");
    gets(str);
    printf("You entered: %s\n", str);
    return 0;
}

In this example, only 10 characters are allotted to the buffer str in this case. The input will go beyond the array's boundaries if the user inputs more than nine characters (including the null terminator). This causes a buffer overflow, in which memory that is not allotted gets overwritten. 

The software may crash, or an attacker may be able to insert malicious code or alter the program's functionality, among other dire outcomes. In the past, several well-publicized security breaches have taken advantage of this type of vulnerability. 

3. Deprecation and Removal

Because of these inherent risks, the C standards committee deprecated gets() in the C99 standard, warning developers against its use. Eventually, in the C11 standard, gets() was completely removed from the language. 

Modern compilers typically display warnings or even errors when gets() is used, and many security-conscious development environments treat its use as a critical issue. Developers are encouraged to replace Gets() in C with safer alternatives, such as fgets(), which require specifying the buffer size and prevent accidental overflows by design.

Alternatives to gets()

Due to the serious security vulnerabilities associated with gets(), it has been deprecated and removed from the C standard. It is highly recommended that developers choose safer alternatives that include appropriate bounds checking and buffer overflow protection. Three often suggested substitutes that are appropriate for various usage situations are listed below.

 1. fgets()

One of the most widely used and safest replacements for Gets() in C is the fgets() function. It prevents buffer overflows by enabling the programmer to select the maximum amount of characters that can be read.

Function Signature:

char *fgets(char *str, int n, FILE *stream);
  • str: A pointer to the character array that will hold the input.
  • n: The null terminator is included in the maximum number of characters that can be read.
  • stream: Input stream (usually stdin for keyboard input).

Example Usage:

#include <stdio.h>

int main() {
    char str[100];
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    printf("You entered: %s", str);
    return 0;
}

fgets() reads up to n - 1 characters and automatically appends a null terminator. However, it also retains the newline character ('\n') when the user presses Enter, which you may want to remove manually.

2. gets_s()

The gets_s() function is a safer version of Gets() in C, introduced in the C11 standard. It improves upon gets() by including a second parameter that specifies the buffer size, offering built-in protection against buffer overflows.

Function Signature:

char *gets_s(char *str, rsize_t n);
  • str: Pointer to the destination buffer.
  • n: Maximum number of characters (buffer size).

In the event of a mistake, gets_s() changes the buffer to an empty string and guarantees that input won't exceed the buffer limit. This function is part of the C11 optional bounds-checking interfaces (Annex K), and its availability may depend on compiler and library support. It is more secure but less portable than fgets().

3. getline()

A strong and adaptable substitute is the getline() function, which is mostly accessible in POSIX-compliant platforms (such as Linux and macOS). Getline() eliminates worries about fixed buffer sizes by dynamically allocating memory to suit the input line, in contrast to gets() or fgets().

Function Signature:

ssize_t getline(char **lineptr, size_t *n, FILE *stream);
  • lineptr: Pointer to a buffer where the input will be stored. If *lineptr is NULL, getline() allocates the memory.
  • n: Pointer to the size of the allocated buffer.
  • stream: Input stream (typically stdin).

getline() automatically resizes the buffer as needed and reads an entire line, including the newline character. It's ideal when handling unpredictable input sizes, such as reading from files or user input without fixed limits. Nevertheless, without further support, it cannot be ported to non-POSIX platforms like Windows since it is not included in the C standard library.

Recap:

  • Use fgets() when writing portable and secure C programs. It is the most widely recommended replacement for gets() and provides explicit control over buffer size.
  • Use gets_s() while working in C11 environments which include Annex K and tight bounds checking is necessary. Compared to fgets(), it is less portable but still secure. 
  • Use getline() when dealing with unknown or variable-length input, especially on POSIX systems like Linux and macOS. It automatically manages memory but is not part of standard C.

Comparison: gets() vs fgets()

The table below highlights the key differences between gets() and fgets(), showing why gets() is unsafe and why fgets() is the preferred choice for secure input handling in C.

Feature gets() fgets()
Buffer Protection Does not limit input length and may cause buffer overflows. Reads only up to a specified number of characters, preventing buffer overflows.
Handling of Newline (\n) Discards the newline character and replaces it with a null terminator. Retains the newline character unless the input exceeds the size limit.
Standard Compliance Deprecated in C99 and removed in C11. Fully supported and recommended in all modern C standards.
Error Handling Weak error detection and may result in undefined behavior. Returns NULL on failure or end-of-file (EOF).
Custom Buffer Size Control No control over input size. Programmer explicitly controls the maximum input size.
Portability Historically portable but unsafe and discouraged. Fully portable across all C compilers and platforms.
Ease of Use Simple syntax but dangerous for real-world programs. Slightly more verbose but safe and reliable.
Security Highly vulnerable to buffer overflow attacks. Secure when used correctly with size limits.
EOF Behavior May behave unpredictably at end-of-file. Cleanly returns NULL at EOF.
Return Value Returns a pointer to the buffer or NULL on failure. Returns NULL on error or EOF, or a pointer to the buffer.
Overall Recommendation Should never be used in modern C programs. Strongly recommended as a safe replacement.

Conclusion

Gets() in C is an invention of the past. Although it was formerly useful for basic input jobs, its lack of safety measures has led to widespread discouragement. All C applications should use safer substitutes like fgets(), gets_s(), and getline().

Developers may create more secure, effective, and portable C programs by using safe programming techniques and being aware of gets(). 

Key Points to Remember 

  1. gets() does not perform bounds checking, which makes it inherently unsafe.
  2. It was deprecated in C99 and removed entirely in C11 due to security risks.
  3. Gets() buffer overflows can result in crashes or exploitable vulnerabilities.
  4. Even with modest inputs, gets() should never be used in modern C applications.
  5. Controlled and safe input handling is provided via functions such as fgets() and getline().

Frequently Asked Questions

1. Why is the gets() function considered unsafe in C?

Users are able to add more data than the input buffer can accommodate since the gets() method does not verify its size. Buffer overflows result from this, which may cause the application to crash or expose security flaws like code injection.

2. When was gets() officially deprecated and removed?

gets() was deprecated in the C99 standard due to its unsafe behavior and was completely removed in the C11 standard. Modern compilers now issue warnings or errors when it's used to discourage its inclusion in new code.

3. What happens if you enter more characters than the buffer size using gets()?

Gets() will write more than the allotted memory if the user inputs more characters than the buffer can hold. Important data might be overwritten, failures could occur, or vulnerabilities like remote code execution could be made possible.

4. What is a safer alternative to gets() in C?

Fgets() is a safer option that lets you define the buffer size. By reading just up to the designated amount of characters and making sure the string is correctly null-terminated, it avoids buffer overflows.

5. Does gets() remove the newline character from input?

Yes, gets() removes the newline character ('\n') from input. It stops reading when a newline is encountered and replaces it with a null terminator to end the string correctly.

6. How does fgets() differ from gets() in behavior?

Unlike gets(), fgets() includes the newline character in the string unless the input length exceeds the buffer limit. It also requires the programmer to define the maximum number of characters to read, making it safer.

7. Can gets() still be used in modern C compilers?

It is strongly advised not to use gets(), even if it could still compile in certain older settings. Because of its well-known security weaknesses, the majority of contemporary compilers either warn against it or refuse to build code that contains it.

Summarise With Ai
ChatGPT
Perplexity
Claude
Gemini
Gork
ChatGPT
Perplexity
Claude
Gemini
Gork
Chat with us
Chat with us
Talk to career expert