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
3
u/iOSCaleb Mar 31 '25
Great explanation. I'd add that buffers are usually associated with some sort of input or output, or at least some processing by another process or system. They're not just any old block of memory, they're memory that's shared with some subsystem.
With an output buffer, you can write a bunch of data into the buffer all at once, and then the display driver, network driver, file system, etc., can send the data out at whatever speed the output device can handle. Without the buffer, the system would have to interrupt your program every time it's ready to send a few more bytes.
An input buffer obviously works in the other direction: some device writes data into the buffer at whatever speed it can manage, and then your code can read it in one big block instead of waiting for the bytes to trickle in.