Skip to content

Conversation

@SuGlider
Copy link
Collaborator

@SuGlider SuGlider commented Oct 12, 2023

Description of Change

A BLEScanResults object is returned from BLEScan methods, causing issues because its same copy is released more than one time, causing HEAP corruption.

To fix it BLEScanResults should be used as a contained class, by reference and not copy.
This is the same done with BLEScan*, for instance.

Tests scenarios

Tested with ESP32 using this sketch that causes the issue, before the change is done (previous version):

#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>

int scanTime = 5; //In seconds
BLEScan* pBLEScan;

void setup() {
  Serial.begin(115200);
  Serial.println("Scanning...");

  BLEDevice::init("");
  pBLEScan = BLEDevice::getScan(); //create new scan
  pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
  pBLEScan->setInterval(100);
  pBLEScan->setWindow(99);  // less or equal setInterval value
}

void myBLEScanFunction() {
  BLEScanResults foundDevices = pBLEScan->start(scanTime, false);
  Serial.print("Devices found: ");
  Serial.println(foundDevices.getCount());
  Serial.println("Scan done!");
  pBLEScan->clearResults();   // delete results fromBLEScan buffer to release memory
}

void loop() {
 myBLEScanFunction(); // crashes when returning from the function with corrupted HEAP
 delay(2000);
}

After the fix, it shall use a BLEScanResults * as reference, instead of the copy of the object as before.

void myBLEScanFunction() {
  BLEScanResults *foundDevices = pBLEScan->start(scanTime, false);
  Serial.print("Devices found: ");
  Serial.println(foundDevices->getCount());
  Serial.println("Scan done!");
  pBLEScan->clearResults();   // delete results fromBLEScan buffer to release memory
}

Related links

Fix #8751

@SuGlider SuGlider added the Area: BLE Issues related to BLE label Oct 12, 2023
@SuGlider SuGlider added this to the 3.0.0 milestone Oct 12, 2023
@SuGlider SuGlider self-assigned this Oct 12, 2023
@SuGlider
Copy link
Collaborator Author

@P-R-O-C-H-Y - This change shuold be added to the migration guide.

Copy link
Member

@lucasssvaz lucasssvaz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@me-no-dev me-no-dev merged commit f218209 into espressif:master Oct 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Area: BLE Issues related to BLE

Projects

Development

Successfully merging this pull request may close these issues.

Crash Memory with Scan BLE if code in an function ( over Version 1.0.6 )

3 participants