Fix: Prevent out-of-bounds memory access in CheckBuildingPlacement

In `CCmpPathfinder::CheckBuildingPlacement`, the boundary check for the
vertical grid dimension (`j > m_TerrainOnlyGrid->m_H`) allowed `j` to equal
`m_TerrainOnlyGrid->m_H`. Since grid indices are 0-based (valid row indices
range from `0` to `m_H - 1`), this boundary condition allowed the loop to
execute with an out-of-bounds row index, leading to an invalid memory
read (`m_TerrainOnlyGrid->get(i, j)`) and potential segfaults.

This patch changes the comparison operator to `j >= m_TerrainOnlyGrid->m_H`,
ensuring that spans extending to or past the grid height bound are properly
flagged as out-of-bounds.
This commit is contained in:
Fabio Pedretti
2026-08-16 14:59:43 +02:00
committed by Phosit
parent e4e50d7711
commit 4dfdfc12b2
@@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@@ -1051,7 +1051,7 @@ ICmpObstruction::EFoundationCheck CCmpPathfinder::CheckBuildingPlacement(const I
i16 j = span.j;
// Fail if any span extends outside the grid
if (i0 < 0 || i1 > m_TerrainOnlyGrid->m_W || j < 0 || j > m_TerrainOnlyGrid->m_H)
if (i0 < 0 || i1 > m_TerrainOnlyGrid->m_W || j < 0 || j >= m_TerrainOnlyGrid->m_H)
return ICmpObstruction::FOUNDATION_CHECK_FAIL_TERRAIN_CLASS;
// Fail if any span includes an impassable tile