Immediate `std::out_of_range` Exception via Use-After-Move in `Grid` Sector Constructor
- Subsystem: Pathfinding Navigation Engine (
libopenage/pathfinding) - Affected File:
libopenage/pathfinding/grid.cpp, lines 30–41 - Severity: High (Unconditional Initialization Crash)
Description & Root Cause
In libopenage/pathfinding/grid.cpp, Grid provides a constructor overload allowing caller-supplied sectors:
Grid::Grid(grid_id_t id,
const util::Vector2s &size,
std::vector<std::shared_ptr<Sector>> &§ors) :
id{id},
size{size},
sectors{std::move(sectors)} {
ENSURE(this->sectors.size() == size[0] * size[1],
"Grid has size " << size[0] << "x" << size[1] << " (" << size[0] * size[1] << " sectors), "
<< "but only " << this->sectors.size() << " sectors were provided");
this->sector_size = sectors.at(0)->get_cost_field()->get_size();
}
In the member initializer list on line 35:
sectors{std::move(sectors)}
The vector is moved from the parameter sectors into the class member this->sectors. Under C++ standard move semantics, the argument sectors is left in a valid but empty moved-from state (sectors.empty() == true).
On line 40 inside the constructor body:
this->sector_size = sectors.at(0)->get_cost_field()->get_size();
The code accesses sectors.at(0) on the moved-from argument sectors instead of this->sectors.at(0).
Because sectors is empty, std::vector::at(0) unconditionally throws std::out_of_range. It is impossible to instantiate Grid using custom sectors without crashing.
Steps to Reproduce
- Instantiate a vector with 4 valid
Sectorpointers for a 2x2 grid. - Call
openage::path::Grid grid(1, util::Vector2s{2, 2}, std::move(sectors));. - The constructor throws
std::out_of_range: vector::_M_range_check: __n (which is 0) >= this->size() (which is 0).
Expected Behavior
this->sector_size should be initialized from the newly populated member this->sectors.at(0).
Suggested Fix
--- a/libopenage/pathfinding/grid.cpp
+++ b/libopenage/pathfinding/grid.cpp
@@ -37,5 +37,5 @@ Grid::Grid(grid_id_t id,
"Grid has size " << size[0] << "x" << size[1] << " (" << size[0] * size[1] << " sectors), "
<< "but only " << this->sectors.size() << " sectors were provided");
- this->sector_size = sectors.at(0)->get_cost_field()->get_size();
+ this->sector_size = this->sectors.at(0)->get_cost_field()->get_size();
}
thanks, would you mind sending a PR as well?