Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This example uses the getchar() function to read in a character at a time from stdin, instead of reading the entire line at once. The stdin stream is read until end-of-file is encountered or a new-line character is read. Any new-line character is discarded, and a null character is written immediately after the last character read into the array. Similar to the previous example, there are no guarantees that this code will not result in a buffer overflow. Note that BUFSIZ is a macro integer defined in cstdio which represents a suggested value for setbuf() and not the maximum size of such an input buffer.

Code Block
bgColor#FFCCCC
langcpp
char buf[BUFSIZ], *p;
int ch;
p = buf;
while ( ((ch = getchar()) != '\n')
       && !feof(stdin)
       && !ferror(stdin))
{
  *p++ = ch;
}
*p++ = 0;

...

In this compliant solution, characters are no longer copied to buf once index = BUFFERSIZE, leaving room to null terminate the string. The loop continues to read through to the end of the line until the end of the file is encountered or an error occurs.

Code Block
bgColor#ccccff
langcpp
unsigned char buf[BUFFERSIZE];
int ch;
int index = 0;
int chars_read = 0;
while ( ( (ch = getchar()) != '\n')
        && !feof(stdin)
        && !ferror(stderr) )
{
  if (index < BUFFERSIZE-1) {
    buf[index++] = (unsigned char)ch;
  }
  chars_read++;
} /* end while */
buf[index] = '\0';  /* terminate NTBS */
if (feof(stdin)) {
  /* handle EOF */
}
if (ferror(stdin)) {
  /* handle error */
}
if (chars_read > index) {
  /* handle truncation */
}

...

Wiki Markup
According to Section 7.19.7.7 of C99 \[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\], the {{gets()}} function reads characters from the {{stdin}} into a destination array until end-of-file is encountered or a new-line character is read.  Any new-line character is discarded, and a null character is written immediately after the last character read into the array.

Code Block
bgColor#FFCCCC
langcpp
char buf[BUFSIZ];
if (gets(buf) == NULL) {
  /* Handle Error */
}

...

The fgets() function reads, at most, one less than a specified number of characters from a stream into an array. This example is compliant because the number of bytes copied from stdin to buf cannot exceed the allocated memory.

Code Block
bgColor#ccccff
langcpp
char buf[BUFFERSIZE];
int ch;
char *p;

if (fgets(buf, sizeof(buf), stdin)) {
  /* fgets succeeds, scan for newline character */
  p = strchr(buf, '\n');
  if (p) {
    *p = '\0';
  }
  else {
    /* newline not found, flush stdin to end of line */
    while (((ch = getchar()) != '\n')
          && !feof(stdin)
          && !ferror(stdin)
    );
  }
}
else {
  /* fgets failed, handle error */
}

...

Wiki Markup
According to TR 24731 \[[ISO/IEC TR 24731-2006|AA. Bibliography#ISO/IEC TR 24731-2006]\]:
<blockquote><p>No additional characters are read after a new-line character (which is discarded) or after end-of-file. The discarded new-line character does not count towards number of characters read. A null character is written immediately after the last character read into the array.</p></blockquote>If end-of-file is encountered and no characters have been read into the destination array, or if a read error occurs during the operation, then the first character in the destination array is set to the null character and the other elements of the array take unspecified values.

Code Block
bgColor#ccccff
langcpp
char buf[BUFFERSIZE];

if (gets_s(buf, sizeof(buf)) == NULL) {
  /* handle error */
}

...

The scanf() function is used to read and format input from stdin. Improper use of scanf() may result in an unbounded copy. In the code below, the call to scanf() does not limit the amount of data read into buf. If more than 9 characters are read, then a buffer overflow occurs.

Code Block
bgColor#FFCCCC
langcpp
enum { CHARS_TO_READ = 9 };

char buf[CHARS_TO_READ + 1];
scanf("%s", buf);

...

The number of characters read by scanf() can be bounded by using the format specifier supplied to scanf().

Code Block
bgColor#ccccff
langcpp
#define STRING(n) STRING_AGAIN(n)
#define STRING_AGAIN(n) #n

#define CHARS_TO_READ 9

char buf[CHARS_TO_READ + 1];
scanf("%"STRING(CHARS_TO_READ)"s", buf);

...

Since the input is unbounded, the following code could lead to a buffer overflow

Code Block
bgColor#FFcccc
langcpp
char buf[12];
cin >> buf;

...

To solve this problem, one can be tempted to use the width method of the ios_base class, but there still is a trap.

Code Block
bgColor#ffcccc
langcpp
char buf_one[12];
char buf_two[12];
cin.width(12);
cin >> buf_one;
cin >> buf_two;

...

While the following doesn't suffer of the same problem as the previous, it still has some :

Code Block
bgColor#ffcccc
langcpp
char buf_one[12];
char buf_two[12];
cin.width(12);
cin >> buf_one;
cin.width(12);
cin >> buf_two;

...

To avoid this truncation problem, it would be better to use an instance of the string class to store the input, as it is dynamically resized to fit the input.

Code Block
bgColor#ccccff
langcpp
string input;
const char *buf_one;
const char *buf_two;
string string_one;
string string_two;
cin >> string_one;
cin >> string_two;
buf_one = string_one.c_str();
buf_two = string_two.c_str();

...