From 3978870f9f1250c18c01db14f69bcbbccfbeffaf Mon Sep 17 00:00:00 2001 From: TD-er Date: Mon, 16 Sep 2024 11:26:43 +0200 Subject: [PATCH] [WiFiScan] Allow allocation in _scanDone() to fail and prevent memory leak (#10335) * [WiFiScan] Allow allocation to fail and prevent memory leak When there are many AP's seen during a scan, the allocation of `_scanResult` may fail. Thus add `(std::nothrow)` to the `new` call. Also it is possible the array was still present before allocating a new one. * [WiFiScan] Use nullptr instead of 0 As suggested by @me-no-dev --- libraries/WiFi/src/WiFiScan.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/libraries/WiFi/src/WiFiScan.cpp b/libraries/WiFi/src/WiFiScan.cpp index 9ebf28f8fde..ffacc57f093 100644 --- a/libraries/WiFi/src/WiFiScan.cpp +++ b/libraries/WiFi/src/WiFiScan.cpp @@ -48,7 +48,7 @@ uint32_t WiFiScanClass::_scanTimeout = 60000; uint16_t WiFiScanClass::_scanCount = 0; uint32_t WiFiScanClass::_scanActiveMinTime = 100; -void *WiFiScanClass::_scanResult = 0; +void *WiFiScanClass::_scanResult = nullptr; void WiFiScanClass::setScanTimeout(uint32_t ms) { WiFiScanClass::_scanTimeout = ms; @@ -117,13 +117,18 @@ int16_t */ void WiFiScanClass::_scanDone() { esp_wifi_scan_get_ap_num(&(WiFiScanClass::_scanCount)); + if (WiFiScanClass::_scanResult) { + delete[] reinterpret_cast(WiFiScanClass::_scanResult); + WiFiScanClass::_scanResult = nullptr; + } + if (WiFiScanClass::_scanCount) { - WiFiScanClass::_scanResult = new wifi_ap_record_t[WiFiScanClass::_scanCount]; + WiFiScanClass::_scanResult = new (std::nothrow) wifi_ap_record_t[WiFiScanClass::_scanCount]; if (!WiFiScanClass::_scanResult) { WiFiScanClass::_scanCount = 0; } else if (esp_wifi_scan_get_ap_records(&(WiFiScanClass::_scanCount), (wifi_ap_record_t *)_scanResult) != ESP_OK) { delete[] reinterpret_cast(WiFiScanClass::_scanResult); - WiFiScanClass::_scanResult = 0; + WiFiScanClass::_scanResult = nullptr; WiFiScanClass::_scanCount = 0; } } @@ -176,7 +181,7 @@ void WiFiScanClass::scanDelete() { WiFiGenericClass::clearStatusBits(WIFI_SCAN_DONE_BIT); if (WiFiScanClass::_scanResult) { delete[] reinterpret_cast(WiFiScanClass::_scanResult); - WiFiScanClass::_scanResult = 0; + WiFiScanClass::_scanResult = nullptr; WiFiScanClass::_scanCount = 0; } }