22

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?

chema989
  • 3,962
  • 2
  • 20
  • 33
basickarl
  • 37,187
  • 64
  • 214
  • 335
  • 2
    some people decrease their pointers, instead of increasing, up to a point, underflow could happen. almost the same thing as overflow. – Jason Hu Oct 08 '14 at 13:27

3 Answers3

23

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).

dom0
  • 7,356
  • 3
  • 28
  • 50
7

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.

5gon12eder
  • 24,280
  • 5
  • 45
  • 92
  • The usage of this word is incorrect, since what you describe is more of a buffer underread. – Max Feb 26 '21 at 06:14
0

There are some examples in PVS V512. I got the issue in gearmad implementation in snippet:

  pollfd fds[2];
  ...
  memset(fds, 0, sizeof(pollfd));
palik
  • 2,425
  • 23
  • 31