while(1)
{
printf("\nEnter message : ");
gets(message);
//Send some data
if( send(sock , message , strlen(message) , 0) < 0)
{
puts("Send failed");
return 1;
}
//Receive a reply from the server
if( recv(sock , server_reply , 2000 , 0) < 0)
{
puts("recv failed");
break;
}
puts("Server reply :");
puts(server_reply);
}
close(sock);
return 0;
}
This is part of my program. When I compile and run it, I get an error. The error's message is
warning: the gets function is dangerous and should not be used!
A simple google search would have given a lot of useful information like this answer.
https://stackoverflow.com/a/1694042/2425366
A buffer overflow example using
gets
Input 1
Output
Input 2
Output
Regarding the issue:
gets()
function is dangerous for the risk of buffer overflow and dropped from the standardC
, as perC11
standard. Compilers may support them for backward compatibility for legacy codes.FWIW, this warning is not issued by
gcc
all by itself. Most likely,glibc
contains a pragma which causes the compiler to emit the warning. RefRegarding the error:
You have
-Werror
enabled in your compilation statement, which basically asksgcc
to treat any warning as error.You didn't show us how you had declared the variable
message
which you passed as the argument togets
. Suppose it wasNow suppose that the actual line of input that your program ends up trying to read is 200 characters long. The array will overflow, with potentially disastrous results. (Seriously: honest-to-goodness major security breaches have resulted from using
gets
.)No matter how big your array is, the input might always be bigger, and there's no way to prevent the overflow, because there's no way to tell
gets
how big your array actually is. That's why you should never use it.