C: What is a/example of a buffer underflow?

basickarl picture basickarl · Oct 8, 2014 · Viewed 18k times · Source

I know what a buffer overflow is. I have no idea however what a buffer underflow is.

I am guessing it is when a specific buffer receives instead of an overflow of bytes, an underflow of bytes.

char buffer[8];
fgets(buffer, sizeof(buffer), stdin);

The above would give no error.

char buffer_overflow[8];
fgets(buffer_overflow, 16, stdin);

The above would result in a buffer overflow if the user input was, for example "deutschland".

Could I get an example in code, what a buffer underflow is?

Answer

dom0 picture dom0 · Oct 8, 2014

A buffer underflow does not relate directly to a buffer overflow. However, buffer underflows can be an issue with e.g. ring buffers.

Consider for example audio playback: your audio buffer is probably a ring buffer somewhere in kernel memory. If you write data slower than the audio driver/hardware reads from the buffer, the buffer becomes empty ("underflows"), leading to stuttering audio. Similar issues exist for other kinds of real-time data processing and media playback, too.

Thus a buffer underflow is often not a fault condition per se (unlike a buffer overflow, which usually causes programs to perform undefined, unwanted behaviour like termination, executing some unwanted code and so on).