esp-nimble-cpp icon indicating copy to clipboard operation
esp-nimble-cpp copied to clipboard

NimBLEScan::clearResults doesn't actually release memory space

Open Zmmfly opened this issue 3 years ago • 1 comments

Hello, I found that when there are too many Bluetooth devices around, the memory usage continues to rise after scanning is turned on.

I called "clearResults" to clean up, but it didn't work, Then I read the code and found that "clear" is only called for "vector" in "clearResults", which doesn't actually free the memory occupied by the vector.

This is a "vector" based memory management problem.

https://github.com/h2zero/esp-nimble-cpp/blob/a36655c105444f26d1ef7dd0893b189ab26f23ce/src/NimBLEScan.cpp#L507-L513 Add a line of code below "clear" to solve: std::vector<NimBLEAdvertisedDevice *>().swap(m_scanResults.m_advertisedDevicesVector);

 void NimBLEScan::clearResults() { 
     for(auto &it: m_scanResults.m_advertisedDevicesVector) { 
         delete it; 
     } 
     m_scanResults.m_advertisedDevicesVector.clear(); 
     std::vector<NimBLEAdvertisedDevice *>().swap(m_scanResults.m_advertisedDevicesVector);
     clearDuplicateCache(); 
 } 

Zmmfly avatar Apr 28 '22 04:04 Zmmfly

I didn't think this would be too much of an issue since the vector would just allocate up to the peak number of devices found and not need to allocate again on the next scan. It's only around 250 bytes for 50 devices, but I will add this anyway.

If you'd like to PR the change feel free to do so.

h2zero avatar Apr 28 '22 17:04 h2zero