gets
Prototype
char* gets(char* s);
This function reads a line of input from the standard input stream (stdin) and stores it in the array pointed to by s
, until either a newline character or the end-of-file is reached. The newline character is replaced with a null character.
Vulnerable example
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char buffer[16]; // create a buffer with 16 bytes of storage
printf("Enter a string: ");
gets(buffer); // read input from the user and store it in buffer
printf("You entered: %s\n", buffer); // print the contents of buffer
return 0;
}
This code creates a buffer with a fixed size of 16 bytes, and then uses the gets
function to read input from the user and store it in the buffer. However, gets
does not check the length of the input, so if the user enters more than 16 characters, the extra characters will overflow the buffer and potentially overwrite other areas of memory, which can lead to unpredictable behavior and security vulnerabilities.
Prevent
To prevent buffer overflow vulnerabilities, it is important to use functions that are designed to check the length of input and limit the amount of data that is read. In this case, the recommended alternative to gets
is fgets
, which takes an additional argument specifying the maximum number of characters to read.
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char buffer[16]; // create a buffer with 16 bytes of storage
printf("Enter a string: ");
fgets(buffer, sizeof(buffer), stdin); // read input from the user and store it in buffer
// remove the newline character from the end of the string
int length = strlen(buffer);
if (buffer[length - 1] == '\n')
buffer[length - 1] = '\0';
printf("You entered: %s\n", buffer); // print the contents of buffer
return 0;
}
This code creates a buffer with a fixed size of 16 bytes, and then uses the fgets
function to read input from the user and store it in the buffer. The fgets
function takes an additional argument specifying the maximum number of characters to read, which in this case is set to the size of the buffer. This ensures that fgets
will not read more characters than the buffer can hold, preventing a buffer overflow.
Last updated