1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

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

Discussion in 'Mac Programming' started by Mugambo, Jul 26, 2012.

  1. Mugambo, Jul 26, 2012
    Last edited by a moderator: Jul 26, 2012

    macrumors 6502

    Mugambo

    #1
    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;
    }
     
  2. macrumors 603

    Cromulent

    #2
    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).
     
  3. macrumors 6502

    Mugambo

    #3
    Thank you for the explanation.
    I replaced gets() with fgets() and the program fails to build.
    Any help please.
     
  4. macrumors 603

    Cromulent

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

    Code:
    man fgets
    this will explain how to use the fgets() function.
     
  5. macrumors 6502

    Mugambo

    #5
    Great! Thanks again!
     
  6. macrumors 603

    #6
    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.
     

Share This Page