From 34717832e2470fe17cf6f3820bbec8e330851ecd Mon Sep 17 00:00:00 2001 From: Eduardo Dantas Date: Sat, 4 Jan 2025 21:02:37 -0300 Subject: [PATCH] fix: add null check for moveFunction to prevent crashes (#3213) This adds a null check for the moveFunction in the MoveEvent::fireAddRemItem method. Previously, the code accessed moveFunction directly without verifying its validity, which could lead to crashes if it was nullptr. The fix ensures stability by: Logging an error message when moveFunction is null. Returning early to prevent further execution with an invalid function pointer. This change improves the reliability of the function, particularly in scenarios where moveFunction might not be properly initialized. --- src/lua/creature/movement.cpp | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/lua/creature/movement.cpp b/src/lua/creature/movement.cpp index 6804cdfa7e9..51daea8cf1e 100644 --- a/src/lua/creature/movement.cpp +++ b/src/lua/creature/movement.cpp @@ -808,6 +808,13 @@ uint32_t MoveEvent::fireAddRemItem(const std::shared_ptr &item, const std: if (isLoadedScriptId()) { return executeAddRemItem(item, fromTile, pos); } else { + if (!moveFunction) { + g_logger().error("[MoveEvent::fireAddRemItem - Item {} item on position: {}] " + "Move function is nullptr.", + item->getName(), pos.toString()); + return 0; + } + return moveFunction(item, fromTile, pos); } } @@ -840,6 +847,13 @@ uint32_t MoveEvent::fireAddRemItem(const std::shared_ptr &item, const Posi if (isLoadedScriptId()) { return executeAddRemItem(item, pos); } else { + if (!moveFunction) { + g_logger().error("[MoveEvent::fireAddRemItem - Item {} item on position: {}] " + "Move function is nullptr.", + item->getName(), pos.toString()); + return 0; + } + return moveFunction(item, nullptr, pos); } } @@ -849,9 +863,9 @@ bool MoveEvent::executeAddRemItem(const std::shared_ptr &item, const Posit // onRemoveItem(moveitem, pos) if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[MoveEvent::executeAddRemItem - " - "Item {} item on tile x: {} y: {} z: {}] " + "Item {} item on position: {}] " "Call stack overflow. Too many lua script calls being nested.", - item->getName(), pos.getX(), pos.getY(), pos.getZ()); + item->getName(), pos.toString()); return false; }