1
0
mirror of https://github.com/OpenRCT2/OpenRCT2 synced 2025-12-10 09:32:29 +01:00

Fix invalid null comparison in RideList sort comparator

The previous comparator returned false when either rideLhs or rideRhs was a nullptr, in an attempt to avoid null pointer dereference. However, this causes both comp(a, nullptr) and comp(nullptr, a) to return false, which violates the requirements of a strict weak ordering.

As defined in the C++ standard, the comparator used in std::sort must establish a strict weak ordering. This includes the requirement that the equivalence relation defined as
equiv(a, b) := !comp(a, b) && !comp(b, a) must be transitive.

In the original logic, two non-null elements a and b might be ordered such that comp(a, b) == true but if both comp(a, nullptr) and comp(b, nullptr) return false, then equiv(a, nullptr) == true and equiv(b, nullptr) == true, which implies equiv(a, b) == true. This contradicts comp(a, b) == true and violates transitivity of equiv.

Such violations can lead to undefined behavior in std::sort, including invalid memory access or segmentation faults.

Fix the comparator to consistently treat nullptr as greater than any non-null pointer, by returning rideLhs != nullptr when either pointer is null. This restores transitivity and compliance with the C++ standard, ensuring reliable and predictable sorting behavior.
This commit is contained in:
Kuan-Wei Chiu
2025-06-23 01:33:57 +08:00
committed by GitHub
parent 51a5cff021
commit 339f3ac755

View File

@@ -818,7 +818,7 @@ namespace OpenRCT2::Ui::Windows
const Ride* rideRhs = GetRide(rhs.Id);
if (rideLhs == nullptr || rideRhs == nullptr)
{
return false;
return rideLhs != nullptr;
}
return !pred(*rideLhs, *rideRhs);
});