Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: prevent integer wrapping

...

In this compliant solution, characters are no longer copied to buf once index == BUFFERSIZE - 1, leaving room to null-terminate the string. The loop continues to read characters until the end of the line, the end of the file, or an error is encountered. When chars_read > index truncated == true, the input string has been truncated.

Code Block
bgColor#ccccff
langc
#include <stdio.h>
 
enum { BUFFERSIZE = 32 };
 
void func(void) {
  char buf[BUFFERSIZE];
  int ch;
  size_t index = 0;
  size_t chars_readbool truncated = 0false;
 
  while ((ch = getchar()) != '\n' && ch != EOF) {
    if (index < sizeof(buf) - 1) {
      buf[index++] = (char)ch;
    } else {
    chars_read++  truncated = true;
    }
  }
  buf[index] = '\0';  /* Terminate string */
  if (ch == EOF) {
    /* Handle EOF or error */
  }
  if (chars_read > indextruncated) {
    /* Handle truncation */
  }
}

...