Safe Version of gets()

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Dave Sinkula Dave Sinkula is offline Offline Jun 4th, 2005, 3:59 pm |
0
Never use the function gets. Why? It is unsafe. Since the maximum string size cannot be specified, it is always susceptible to buffer overflow.

This snippet shows one way to do a safe version of gets. It reads characters from the stdin into a string up to the specified size and discards the trailing newline. It does not remove excess characters from the stdin either.

See also Read a Line of Text from the User.
Quick reply to this message  
C Syntax
  1. #include <stdio.h>
  2.  
  3. char *sgets(char *line, size_t size)
  4. {
  5. size_t i;
  6. for ( i = 0; i < size - 1; ++i )
  7. {
  8. int ch = fgetc(stdin);
  9. if ( ch == '\n' || ch == EOF )
  10. {
  11. break;
  12. }
  13. line[i] = ch;
  14. }
  15. line[i] = '\0';
  16. return line;
  17. }
  18.  
  19. int main(void)
  20. {
  21. int i;
  22. for ( i = 0; i < 3; ++i )
  23. {
  24. char text[20] = "";
  25. fputs("prompt: ", stdout);
  26. fflush(stdout);
  27. printf("text = \"%s\"\n", sgets(text, sizeof text));
  28. }
  29. return 0;
  30. }
  31.  
  32. /* my input/output
  33. prompt: 1234567890123456789012345
  34. text = "1234567890123456789"
  35. prompt: text = "012345"
  36. prompt: hello world
  37. text = "hello world"
  38. */

Message:


Thread Tools Search this Thread



Tag cloud for C
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC