PDA

View Full Version : warning: this program uses gets(), which is unsafe.




Mugambo
Jul 26, 2012, 05:22 AM
For the following program, xcode compiles and runs the program fine but gives the aforementioned error. Why is it bad to use gets()?

Here is the program for which xcode gave the error:

Converting lowercase string to uppercase:


#include <stdio.h>

int main(int argc, const char * argv[])
{

// insert code here...
char str[100], i;
printf("Enter a string");
gets(str);
for(i=0;i<100 ; )
{
if((str[i]>=97)&&(str[i]<=123))
str[i]-=32;
i++;
}
printf("%s", str);
return 0;
}



Cromulent
Jul 26, 2012, 05:35 AM
You should never use gets() as it is a dangerous function. The reason is that it does not allow you to state how big your buffer is so it is very easy to get a buffer overflow when using it.

Use fgets() instead.

Edit: In C11 the gets() function has been removed from the standard completely and if compiling in strict C11 mode it should not even exist (although I have a nasty feeling that most implementations will continue to support it even though it has been removed).

Mugambo
Jul 26, 2012, 06:06 AM
Thank you for the explanation.
I replaced gets() with fgets() and the program fails to build.
Any help please.

Cromulent
Jul 26, 2012, 06:09 AM
Thank you for the explanation.
I replaced gets() with fgets() and the program fails to build.
Any help please.

fgets() has a different signature than gets(). Read the documentation for it by typing the following in a terminal window:

man fgets

this will explain how to use the fgets() function.

Mugambo
Jul 26, 2012, 06:13 AM
Great! Thanks again!

chown33
Jul 26, 2012, 11:13 AM
Great! Thanks again!

I just wanted to point out that both questions, "Why is gets unsafe?", and "Use of fgets", could have been answered by googling the text of the question. Go ahead, try it.

It's good to get used to finding answers yourself, even ones you think you might not find an answer for.