Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Mugambo

macrumors 6502
Original poster
Jul 4, 2009
286
0
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:


Code:
#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;
}
 
Last edited by a moderator:

Cromulent

macrumors 604
Oct 2, 2006
6,802
1,096
The Land of Hope and Glory
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

macrumors 6502
Original poster
Jul 4, 2009
286
0
Thank you for the explanation.
I replaced gets() with fgets() and the program fails to build.
Any help please.
 

chown33

Moderator
Staff member
Aug 9, 2009
10,740
8,416
A sea of green
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.