Something in C that has always bothered me.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jonniethecodeprince
    New Member
    • Mar 2007
    • 35

    Something in C that has always bothered me.

    Hi guys,

    Just a quick question really regarding using strings in C.

    I know that a very good way in to capture and display a string in C is to use the gets() function. I know this used to be all the rage in C but now its frowned upon and some compilers now pick upon this as a warning error.

    For example if you were to write something like
    [CODE="c"]printf("\nTown name: ");
    gets(address.to wn, 25, stdin);
    address.town[strlen(address. town) -1] = '\0';
    puts(address.to wn);[/CODE]

    some compilers now pick this up as bad practice. What bugs me is what alternative function could you now use to grab and display a string in C is gets() is so bad?

    Thanks
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    Try fgets() instead, it takes a parameter of the maximum number of characters allowed to be read (usually the array size).

    Gets is bad because it doesn't check the size of the input string against the size of the array, it just writes. So if the string is larger, then important things start to get overwritten, like the location of where in the set of machine instructions the function should return to.

    Comment

    Working...