Skip to content

Commit

Permalink
[WiFiScan] Allow allocation in _scanDone() to fail and prevent memory…
Browse files Browse the repository at this point in the history
… 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
  • Loading branch information
TD-er authored Sep 16, 2024
1 parent 44a4844 commit 3978870
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions libraries/WiFi/src/WiFiScan.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -117,13 +117,18 @@ int16_t
*/
void WiFiScanClass::_scanDone() {
esp_wifi_scan_get_ap_num(&(WiFiScanClass::_scanCount));
if (WiFiScanClass::_scanResult) {
delete[] reinterpret_cast<wifi_ap_record_t *>(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<wifi_ap_record_t *>(WiFiScanClass::_scanResult);
WiFiScanClass::_scanResult = 0;
WiFiScanClass::_scanResult = nullptr;
WiFiScanClass::_scanCount = 0;
}
}
Expand Down Expand Up @@ -176,7 +181,7 @@ void WiFiScanClass::scanDelete() {
WiFiGenericClass::clearStatusBits(WIFI_SCAN_DONE_BIT);
if (WiFiScanClass::_scanResult) {
delete[] reinterpret_cast<wifi_ap_record_t *>(WiFiScanClass::_scanResult);
WiFiScanClass::_scanResult = 0;
WiFiScanClass::_scanResult = nullptr;
WiFiScanClass::_scanCount = 0;
}
}
Expand Down

0 comments on commit 3978870

Please sign in to comment.