| | |
Safe Version of gets()
Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Never use the function
This snippet shows one way to do a safe version of
See also Read a Line of Text from the User.
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.
#include <stdio.h> char *sgets(char *line, size_t size) { size_t i; for ( i = 0; i < size - 1; ++i ) { int ch = fgetc(stdin); if ( ch == '\n' || ch == EOF ) { break; } line[i] = ch; } line[i] = '\0'; return line; } int main(void) { int i; for ( i = 0; i < 3; ++i ) { char text[20] = ""; fputs("prompt: ", stdout); fflush(stdout); printf("text = \"%s\"\n", sgets(text, sizeof text)); } return 0; } /* my input/output prompt: 1234567890123456789012345 text = "1234567890123456789" prompt: text = "012345" prompt: hello world text = "hello world" */
Similar Threads
- Bug in latest version of plot.py (wx version 2.8)... (Python)
- PHP/MySQL Update table from offline version to online version (PHP)
- Safe Array within a Safe Array Implementation (C++)
- fatal error C1900: Il mismatch between 'P1' version '20060201' and 'P2' version '2005 (C++)
- Failing with the as version and msi version could not be installed. (Perl)
| Thread Tools | Search this Thread |
Tag cloud for C
adobe ansi api array arrays asterisks bash binarysearch calculate centimeter char convert copyanyfile copyimagefile copypdffile cprogramme createcopyoffile csyntax directory dynamic fflush file fork frequency getlasterror givemetehcodez global graphics gtkgcurlcompiling hacking hardware highest homework i/o inches incrementoperators infiniteloop initialization interest km lazy linked linkedlist linux linuxsegmentationfault list locate logical_drives match matrix meter microsoft motherboard multi mysql number open opendocumentformat opensource owf pattern pdf performance pointer pointers posix power problem probleminc program programming pyramidusingturboccodes read recursion recv repetition scanf scheduling scripting segmentationfault send shape socketprograming spoonfeeding stack standard string strings structures suggestions systemcall test testautomation unix user variable voidmain() wab win32api windows.h



