gets
Prototype
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
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.
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.
Note that the fgets
function includes the newline character in the input, so the code above removes the newline character from the end of the string before printing it.
Last updated