Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a buffer?

As far as my understanding of languages goes, a buffer is any portion of memory in which a data is stored like an int,float variables, character arrays etc. However, I was reading buffer overflows and came across this link while reading about stack http://www.tenouk.com/Bufferoverflowc/Bufferoverflow2a.html The diagram in this link separates buffer from local variables of a function. Is this correct? What's a buffer then?

like image 617
Naruto Avatar asked Jul 17 '10 18:07

Naruto


1 Answers

Very abstract analogy: Local variables are what you're working with right now; they're what you're holding in your hands. A buffer is to a data source as a spoon is to a soup bowl, or a measuring cup is to a water tap. It's more practical to be holding a spoon in your hands than it is to be holding a soup bowl in your hands, and it's virtually impossible to be holding a running stream of water in your hands. In either case, you're using these utensils so that you can consume the soup/water in a pace that suits you.

More concretely, local variables are simply the variables that you've declared inside a function as opposed to outside. A buffer is a chunk of memory (usually an array) that's used to copy a small chunk of data from a huge data source, so you can process it at whatever pace your computer or program can handle. You might declare the buffer outside of your function if you want another function to fill it up, or you might declare it as a local variable if you're going to be filling it up and using it yourself. It's a really general term.

Some examples:

  • An audio buffer might hold about 0.5 seconds worth of audio to copy from the sound card to the program's memory for the program to process, or from the program's memory to the sound card for output to the speakers. Your program could immediately decode an mp3 file and dump all the data at your card, but it would end up being on the order of a few hundred MB if it did that, and you wouldn't enjoy listening to music at 50x speed -- so it decodes just little by little, and stores it in a buffer.
  • A video buffer might be filled up in your memory and/or hard disk from YouTube when you start a video, so that you're not pausing every few seconds because the internet connection's too slow.
  • A program might use a character buffer to share some text from one function to another. If you use cin or ReadLine or gets or something to get some text input from the keyboard, it would be fair to call the string that it gets stored in a "character buffer". In this case, you'd declare the buffer as a local variable.
like image 111
Rei Miyasaka Avatar answered Oct 13 '22 21:10

Rei Miyasaka