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
7
u/Scoutron Mar 30 '25
Comments like these are incredibly helpful when you google or reddit search and end up in a thread with your exact question and this is all you see.
This isn’t exactly a very busy sub, so asking beginner-intermediate level questions and getting to talk one on one to other people who are farther along in your field about them is more useful than just reading the Wikipedia article on “memory buffers.”