Summary
The dynamic interval kind's operator- (interval distance) computes the distance but never returns it. The function is declared to return value_type, so falling off the end is undefined behavior: under -O1 and above it typically returns a garbage value or crashes.
Root cause
// include/interval-tree/interval_tree.hpp:348-351 (dynamic interval kind)
value_type operator-(interval const& other) const
{
interval_kind::distance(*this, other); // result computed but NOT returned
}Compare the correct closed-interval implementation in the same header (lines 210–219), which returns in every path:
value_type operator-(interval const& other) const
{
if (overlaps(other)) return0;
if (high_ <= other.low_) return other.low_ - high_;
elsereturn low_ - other.high_;
}The bug is also a compile-time diagnostic: -Wreturn-type (on by default in clang/gcc) warns here, and the build fails under -Werror.
Steps to reproduce
#include<interval-tree/interval_tree.hpp>usingnamespacelib_interval_tree;using Dyn = interval<int, dynamic>;
Dyn a(1, 5, interval_border::closed, interval_border::closed);
Dyn b(7, 9, interval_border::closed, interval_border::closed);
auto d = a - b; // non-overlapping; distance should be 2// EXPECTED: d == 2// ACTUAL: UBSan: "reached end of value-returning function"; garbage / SIGSEGV under -O1
Compile with -O1 -fsanitize=undefined to observe the report.
Expected vs. actual
- Expected:
operator- returns the interval distance (0 for overlapping intervals; a positive gap otherwise), as documented in the header comment ("Calculates the distance between the two intervals"). - Actual: no value is returned; behavior is undefined.
Suggested fix
return interval_kind::distance(*this, other);
Summary
The
dynamicinterval kind'soperator-(interval distance) computes the distance but never returns it. The function is declared to returnvalue_type, so falling off the end is undefined behavior: under-O1and above it typically returns a garbage value or crashes.Root cause
Compare the correct closed-interval implementation in the same header (lines 210–219), which returns in every path:
The bug is also a compile-time diagnostic:
-Wreturn-type(on by default in clang/gcc) warns here, and the build fails under-Werror.Steps to reproduce
Compile with
-O1 -fsanitize=undefinedto observe the report.Expected vs. actual
operator-returns the interval distance (0 for overlapping intervals; a positive gap otherwise), as documented in the header comment ("Calculates the distance between the two intervals").Suggested fix