From e6249623d5482206a24f153c1e3b09d466d44892 Mon Sep 17 00:00:00 2001 From: h2zero Date: Sun, 12 Jan 2025 16:33:19 -0700 Subject: [PATCH] Fix race condition in NimBLEScan::clearResults. If clear results is called from more than one task a race condition exists that may delete the same advertisedDevice twice. This prevents this by swapping with an empty vector and testing for empty before freeing the resources. --- src/NimBLEScan.cpp | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/NimBLEScan.cpp b/src/NimBLEScan.cpp index 16b46cf..60e7db2 100644 --- a/src/NimBLEScan.cpp +++ b/src/NimBLEScan.cpp @@ -468,10 +468,15 @@ NimBLEScanResults NimBLEScan::getResults() { * @brief Clear the stored results of the scan. */ void NimBLEScan::clearResults() { - for (const auto& dev : m_scanResults.m_deviceVec) { - delete dev; + if (m_scanResults.m_deviceVec.size()) { + std::vector vSwap{}; + ble_npl_hw_enter_critical(); + vSwap.swap(m_scanResults.m_deviceVec); + ble_npl_hw_exit_critical(0); + for (const auto& dev : vSwap) { + delete dev; + } } - std::vector().swap(m_scanResults.m_deviceVec); } // clearResults /**