r/computerscience • • Mar 30 '25

What exactly is a "buffer"

I had some very simple C code:

int main() {
  while (1) {
    prompt_choice();
  }
}

void prompt_choice() {
  printf("Enter your choice: ");
  int choice;
  scanf("%d", &choice);
  switch (choice) {
    case 1:
      /* create_binary_file(); */
      printf("your choice %d", choice);
      break;
    default:
      printf("Invalid choice. Please try again.\n");
  }
}

I was playing around with different inputs, and tried out A instead of some valid inputs and I found my program infinite looping. When I input A, the buffer for scanf doesn't clear and so that's why we keep hitting the default condition.

So I understand to some extent why this is infinite looping, but what I don't really understand is this concept of a "buffer". It's referenced a lot more in low-level programming than in higher level languges (e.g., Ruby). So from a computer science perspective, what is a buffer? How can I build a mental model around them, and what are their limitations?

72 Upvotes

26 comments sorted by

View all comments

Show parent comment

-3

u/tcpukl Mar 30 '25

I googled it myself before posting. It described exactly what they were.

If op didn't understand something more specific they should have asked that instead. But since they didn't Google first they couldn't.

5

u/Scoutron Mar 30 '25

I googled it just now and got the very technical Wikipedia definition and a couple stack overflow comments with mid tier explanations or people complaining that it’s a duplicate question.

Meanwhile, another commenter in this thread answered the question in such a beginner friendly way that there’s practically no way anyone wouldn’t be able to understand it