gets() shows warning in gcc compiler - how to remove?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • princesingla
    New Member
    • Jan 2013
    • 1

    gets() shows warning in gcc compiler - how to remove?

    hello
    i want to know ,why the gets() show an warning in gcc compilier,and how to remove the warning
  • Anas Mosaad
    New Member
    • Jan 2013
    • 185

    #2
    What is the warning you are got? It should be working fine as in the below example:
    Code:
    char s [256];
    gets(s);

    Comment

    • Gobi Sakthivel
      New Member
      • Jan 2013
      • 26

      #3
      When you try to compile C code that uses the gets function, You will get a warning: the gets function is dangerous and should not be used.

      In order to use gets safely, you have to know exactly how many characters that you will be reading so you can make your buffer large enough, which we cant be sure.

      A simple example:

      Code:
      char array1[] = "12345";
      char array2[] = "67890";
      
      gets(array1);
      Now, first of all you are allowed to input how many characters you want, gets won't care about it. Secondly the bytes over the size of the array in which you put them (in this case array1) will overwrite whatever they find in memory because gets will write them. In the previous example this means that if you input "abcdefghijklmn opqrts" maybe, unpredictably, it will overwrite also array2 or whatever.

      The function is unsafe because it assumes consistent input. NEVER USE IT!
      Last edited by Rabbit; Jan 22 '13, 04:36 PM. Reason: Please use code tags when posting code.

      Comment

      • Banfa
        Recognized Expert Expert
        • Feb 2006
        • 9067

        #4
        Further to what has been said, indeed never use gets, use fgets instead with stdin as the file stream.

        fgets is better than gets because you specify the size of your input buffer and thus avoid the possibility of overwriting the end of it.

        Comment

        Working...