C Library - gets() function



The C library gets() function is used to read a line from the standard input stream (stdin) and store it into the string pointed to by str. It continues reading characters from the input stream until a newline character is encountered or the end-of-file is reached. The newline character is then replaced by a null terminator, and the resulting string is stored in str.

Syntax

Following is the C library syntax of the gets() function −

char *gets(char *str);

Parameters

This function takes only a single parameter −

  • str : Pointer to the character array where the input string will be stored. It must have enough space to store the input string along with the null terminator.

Return Value

The gets() function returns the same pointer str on success. On failure or end-of-file condition, it returns NULL.

Example 1: Reading a String from Standard Input

This example reads a string from the standard input using gets() and then prints the entered string.

Below is the illustration of C library gets() function.

#include <stdio.h>

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

Output

The above code produces following result−

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

Example 2: Handling Buffer Overflow

This example shows what happens when the input string exceeds the size of the buffer, causing a buffer overflow. Only the first few characters that fit into the buffer are stored, leading to unexpected behavior.

#include <stdio.h>

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

Output

After execution of above code, we get the following result

Enter a string: Overflow
You entered: Over
Advertisements