C Library Functions -gets()

C Standard Library - <stdio.h>


In the C language,gets()It is a classic function used to read strings from standard input. Although it is simple to use, security issues need to be noted.

gets()function fromstandard input stdinIt reads a line of string and stores it in the specified character array. It reads characters until a newline character or end-of-file is encountered.

Important Warning:gets()It has serious security vulnerabilities and cannot specify the buffer size, which can easily lead to buffer overflow. Therefore, in modern C programming,fgets()is a better choice.

Word Definitions:getmeans "get",srepresents "string", and combined together it means "get string".


Basic syntax and parameters

gets()It is a function in the C standard library and requires including the header file.<stdio.h>。

Syntax format

char *gets(char *str);

Parameter description

  • Parameter: str
    • Type:char *(pointer to character array)
    • Description: A pointer to a character array, which is used to store the read C string. You need to ensure the array is large enough to accommodate the input string.

Function description

  • Return Value: If successful, returns a pointer tostrpointer. If an error occurs or the end of the file is reached without reading any characters, it returnsNULL。
  • Effect: The read string (not including the newline character) will be stored instrthe array pointed to, and a null character is automatically appended at the end.\0as the string terminator.

Example

Let's master through examplesgets()Usage.

Example 1: Basic Usage - Reading a String

Example

#include <stdio.h>

int main()
{
   char str[50];

   printf("Please enter a string: ");
   gets(str);

   printf("The string you entered is: %s", str);

   return(0);
}

Expected output:

请输入一个字符串:example
您输入的字符串是:example

Code analysis:

  1. #include <stdio.h>is to usegets()Prerequisite of the function.
  2. char str[50];It defines a character array of length 50 to store the input string.
  3. gets(str);It reads a line of string from standard input and stores it instrIn.
  4. printf("您输入的字符串是:%s", str);Usage%sformat specifiers output strings.

Example 2: Handling the Case Where the Return Value Is NULL

In actual programming, you should checkgets()the return value to handle possible errors.

Example

#include <stdio.h>

int main()
{
   char str[100];
   char *result;

   printf("Please enter some content (press Ctrl+D to end):\n");
   result = gets(str);

   if (result != NULL) {
       printf("Read successfully, the content is:\n%s\n", str);
   } else {
       printf("Read failed or the end of the file was reached!\n");
   }

   return(0);
}

Code analysis:

  • gets()It returns a pointer to the same string; if it fails, it returnsNULL。
  • When the user presses Ctrl+D (Linux/Mac) or Ctrl+Z (Windows), the end-of-file condition is triggered,gets()returnNULL。
  • In real projects, it is recommended to use the saferfgets()Alternativegets()。

Example 3: Security Issues of gets() (⚠️ Demonstrating Dangerous Operations)

The following example shows whygets()is unsafe.

Example

#include <stdio.h>

int main()
{
   // Note: this example is dangerous and is for demonstration only!
   char buffer[10];

   printf("Please enter a longer string (more than 10 characters):\n");
   gets(buffer);  // No bounds checking, may cause buffer overflow

   printf("You entered: %s\n", buffer);

   return(0);
}

Code analysis:

  • buffer[10]Only 10 bytes of space are allocated.
  • If the user inputs a string exceeding 9 characters (plus the trailing\0), it will causeBuffer Overflow, may overwrite adjacent memory areas.
  • This can be exploited by attackers to execute malicious code; therefore,gets()It was marked as deprecated in the C99 standard and was even removed in the C11 standard.

Better Alternative: fgets()

It is strongly recommended to usefgets()insteadgets(), because it can specify the buffer size.

Example

#include <stdio.h>

int main()
{
   char str[50];

   printf("Please enter a string: ");
   // fgets(buffer, buffer size, file stream)
   fgets(str, sizeof(str), stdin);

   // Remove the newline character read by fgets
   // Method: find the newline character and replace it with a null character
   for (int i = 0; str[i] != '\0'; i++) {
       if (str[i] == '\n') {
           str[i] = '\0';
           break;
       }
   }

   printf("The string you entered is: %s\n", str);

   return(0);
}

fgets()Advantages:

  • It can specify the maximum number of characters to read, preventing buffer overflow.
  • It retains the newline character at the end of the string (can be manually removed if needed).
  • It can specify the input source (standard input, file, etc.).

C Standard Library - <stdio.h>

other extensions