`gets()` in C is considered unsafe because it can lead to buffer overflow vulnerabilities. This happens when the function doesn't check if the input exceeds the allocated memory buffer.
Key Issue: If the input exceeds the size of the buffer, it overwrites other memory regions, which can cause undefined behavior, crashes, or security vulnerabilities like stack corruption.
gets(buffer); (unsafe in C)
If you declare a buffer of size 10 but the user enters 20 characters, gets() will allow writing past the buffer’s boundary, which causes overflow.
char buffer[10];
gets(buffer); // Dangerous if input is more than 10 characters
In the above example, the input exceeds the buffer's allocated size, leading to undefined behavior or memory corruption.
In C, a safer alternative to `gets()` is `fgets()`, which allows you to specify the buffer size, preventing overflow.
char buffer[20];
fgets(buffer, sizeof(buffer), stdin); // Safer than gets()
In this example, `fgets()` ensures that no more than `sizeof(buffer)-1` characters are read, including the null-terminator.
`readln()` in Pascal automatically handles input size by reading data into a variable that has a fixed size. It prevents buffer overflow because the input is constrained to the variable’s type and size.
If you declare a variable as string[20], `readln()` will ensure that only 20 characters are accepted, discarding any excess input.
program SafeInput;
var
name: string[20];
begin
writeln('Enter your name:');
readln(name); // Only up to 20 characters will be accepted
writeln('Hello, ', name);
end.
This makes Pascal's `readln()` more predictable and secure compared to `gets()` in C.
In summary: