From ba9d79a01ae88da0ded42f4f30618856cda52e8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Bergstr=C3=B6m?= <david.bergstrom@liu.se> Date: Wed, 20 Dec 2023 11:28:11 +0100 Subject: [PATCH] Fix segfault errors in getTarget and hasTarget on Linux --- src/IDABot.cpp | 2 +- src/Unit.cpp | 43 ++++++++++++++++++++++++++++++------------- 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/src/IDABot.cpp b/src/IDABot.cpp index 8a5fbf7ef..27ea3d8f4 100644 --- a/src/IDABot.cpp +++ b/src/IDABot.cpp @@ -383,4 +383,4 @@ float IDABot::UpgradeResearchTime(sc2::UpgradeID upgrade_id) const float IDABot::RadiusEffect(sc2::EffectID effect_id) const { return Observation()->GetEffectData()[effect_id].radius; -} \ No newline at end of file +} diff --git a/src/Unit.cpp b/src/Unit.cpp index 130eaa318..71b10ef8e 100644 --- a/src/Unit.cpp +++ b/src/Unit.cpp @@ -337,16 +337,27 @@ Unit Unit::getTarget() const BOT_ASSERT(isValid(), "Unit is not valid"); // if unit has order, check tag of target of first order if(getUnitPtr()->orders.size() > 0){ - // t_id is set to the unit tag of the target - CCUnitID t_id = getUnitPtr()->orders[0].target_unit_tag; - - // if it doesn't have a target. Return itself - if (m_bot->GetUnit(t_id) == nullptr) { - return *this; - } + // t_id is set to the unit tag of the target + CCUnitID t_id = getUnitPtr()->orders[0].target_unit_tag; + + // Make sure the returned tag is not the NullTag + if (t_id == sc2::NullTag) { + return *this; + } + + // Make sure the Tag references a valid unit + if (m_bot->Observation()->GetUnit(t_id) == nullptr) { + return *this; + } - // IDABot finds the unit with this tag - return m_bot->GetUnit(t_id); + // Convert the tag to a Unit object + Unit unit = m_bot->GetUnit(t_id); + + if (unit.isValid()) { + return unit; + } else { + return *this; + } } return *this; } @@ -356,10 +367,16 @@ bool Unit::hasTarget() const BOT_ASSERT(isValid(), "Unit is not valid"); if (getUnitPtr()->orders.size() > 0) { - if (getUnitPtr()->orders[0].target_unit_tag != NULL) { + if (getUnitPtr()->orders[0].target_unit_tag != sc2::NullTag) { CCUnitID t_id = getUnitPtr()->orders[0].target_unit_tag; - // IDABot finds the unit with this tag, and returns true if valid - return m_bot->GetUnit(t_id).isValid(); + + if (m_bot->Observation()->GetUnit(t_id) == nullptr) { + return false; + } + + Unit unit = m_bot->GetUnit(t_id); + + return unit.isValid(); } } @@ -504,4 +521,4 @@ float Unit::maxShields() const float Unit::maxEnergy() const { return m_unit->energy_max; -} \ No newline at end of file +} -- GitLab