openage icon indicating copy to clipboard operation
openage copied to clipboard

Immediate `std::out_of_range` Exception via Use-After-Move in `Grid` Sector Constructor

Open codeCraft-Ritik opened this issue 1 month ago • 1 comments


  • 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>> &&sectors) :
	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

  1. Instantiate a vector with 4 valid Sector pointers for a 2x2 grid.
  2. Call openage::path::Grid grid(1, util::Vector2s{2, 2}, std::move(sectors));.
  3. 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();
 }

codeCraft-Ritik avatar Oct 28 '26 04:10 codeCraft-Ritik

thanks, would you mind sending a PR as well?

TheJJ avatar Nov 01 '26 23:11 TheJJ