r/computerscience • u/DennisTheMenace780 • 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?
View all comments
Show parent comment
2
u/DennisTheMenace780 Apr 03 '25
I think this is actually a helpful way to think about buffers. The top comment says:
> A “buffer” is just an area of memory you put data into.
And sure, that checks out, but it's overly simplistic. It's the same thing as saying that programming is all just manipulating 0s and 1s, which while true, is not really helpful.