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?
Opposite of a buffer overflow, this type of error arises when the flow of data from the original source, typically the hard drive, was interrupted long enough for the buffer to reach full capacity and empty itself. As a result, the writing action is stopped and the device receiving the data may be ruined.
The check reports overflow when accessed memory is beyond the end of the buffer, and underflow when the accessed memory is before the beginning of a buffer.
Address Sanitizer Error: Stack buffer underflow. These error messages indicate a memory access to somewhere before the beginning of a stack variable.
Underflow is a condition or exception that results if a number calculation is too small to be represented by the CPU or memory. It may be caused by a limitation of the computer's hardware, its architecture, or the data type of the numbers used in the calculation.
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).
I have occasionally heard the term be used to refer to erroneously reading ahead of the beginning of a buffer. I don't know whether this usage of the word is “correct”.
As an example, consider this flawed implementation of a stack.
struct fixed_size_stack
{
int top;
int data[128];
};
int
fixed_size_stack_pop(struct fixed_size_stack * this)
{
return this->data[--(this->top)];
}
The missing check for if (this->top > 0)
will cause the function to read over the lower bound of the array if a pop from an already empty stack is requested.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With