Skip to content

Fix assertion in `postStringLen` to account for \0 byte

Hannes Siebenhandl requested to merge wip/fendor/post-string-len-assertion into master

Before this change, the assertion looked like this:

ASSERT(eb->begin + eb->size > eb->pos + len + 1);

Let's assume some values to see why this is actually off by one:

eb->begin = 0
eb->size  = 1
eb->pos   = 0

len       = 1

then the assertion would trigger correctly:

0 + 1 > 0 + 1 + 1 => 1 > 2 => false

as there is not enough space for the \0 byte (which is the trailing +1). However, if we change eb->size = 2, then we do have enough space for a string of length 1, but the assertion still fails:

0 + 2 > 0 + 1 + 1 => 2 > 2 => false

Which causes the assertion to fail if there is exactly enough space for the string with a trailing \0 byte.

Clearly, the assertion should be >=! If we switch around the operand, it should become more obvious that <= is the correct comparison:

ASSERT(eb->pos + len + 1 <= eb->begin + eb->size);

This is expresses more naturally that the current position plus the length of the string (and the null byte) must be smaller or equal to the overall size of the buffer.

This change also is in line with the implementation in hasRoomForEvent and hasRoomForVariableEvent:

StgBool hasRoomForEvent(EventsBuf *eb, EventTypeNum eNum)
{
  uint32_t size = ...;
  if (eb->pos + size > eb->begin + eb->size)
  ...

the check eb->pos + size > eb->begin + eb->size is identical to eb->pos + size <= eb->begin + eb->size plus a negation.

Edited by Hannes Siebenhandl

Merge request reports

Loading