2
#include<stdio.h>

int main() {
    char arr[10];
    printf("Enter your name: \n");
    fgets(arr, sizeof(arr), stdin);
    puts(arr);
    return 0;
}

I have a char arr[10] and use fgets(arr, sizeof(arr), stdin) to receive input. If I input say 20 characters, 9 chars will be written to arr[10] along with the null terminator added. But what happens to the remaining chars in the buffer? Do they get automatically flushed/cleared or are they left in the buffer forever? i.e. Can extra chars that are outside the bounds check cause a problem?

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61
rain
  • 45
  • 3
  • 1
    If the string placed in the character array by fgets does not contain the new line character then it means that the input buffer contains other characters that you can read using one more call of fgets. – Vlad from Moscow Mar 30 '21 at 20:35
  • 3
    They remain in the input buffer until you read them. They only cause a problem if your program doesn't handle a short read correctly. – William Pursell Mar 30 '21 at 20:37

1 Answers1

1

But what happens to the remaining chars in the buffer?

They remain in stdin for the next read function.

Do they get automatically flushed/cleared or are they left in the buffer forever?

Left in stdin until read or program ends.

Can extra chars that are outside the bounds check cause a problem?

Not directly. It depends on how your program copes will failing to read the excess input.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256