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


    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");
        for(i=0;i<100 ;  )
        printf("%s", str);
        return 0;
  2. macrumors 603


    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


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


    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.
  5. macrumors 6502


    Great! Thanks again!
  6. macrumors 603

    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