From 53db347daf7cde85b855ef61a8bdc93ef05d7cf3 Mon Sep 17 00:00:00 2001 From: Frederic Pillon Date: Thu, 19 Oct 2023 09:24:28 +0200 Subject: [PATCH] fix(Wire): avoid memory leaks add destructor to call end(). Fixes #2142 Signed-off-by: Frederic Pillon --- libraries/Wire/src/Wire.cpp | 21 +++++++++++++++++---- libraries/Wire/src/Wire.h | 1 + 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/libraries/Wire/src/Wire.cpp b/libraries/Wire/src/Wire.cpp index 1d8d3ee556..c0b1a25d7a 100644 --- a/libraries/Wire/src/Wire.cpp +++ b/libraries/Wire/src/Wire.cpp @@ -45,6 +45,15 @@ TwoWire::TwoWire(uint32_t sda, uint32_t scl) _i2c.scl = digitalPinToPinName(scl); } +/** + * @brief TwoWire destructor + * @retval None + */ +TwoWire::~TwoWire() +{ + end(); +} + // Public Methods ////////////////////////////////////////////////////////////// void TwoWire::begin(uint32_t sda, uint32_t scl) @@ -106,11 +115,15 @@ void TwoWire::begin(int address, bool generalCall, bool NoStretchMode) void TwoWire::end(void) { i2c_deinit(&_i2c); - free(txBuffer); - txBuffer = nullptr; + if (txBuffer != nullptr) { + free(txBuffer); + txBuffer = nullptr; + } txBufferAllocated = 0; - free(rxBuffer); - rxBuffer = nullptr; + if (rxBuffer != nullptr) { + free(rxBuffer); + rxBuffer = nullptr; + } rxBufferAllocated = 0; } diff --git a/libraries/Wire/src/Wire.h b/libraries/Wire/src/Wire.h index e5a5d8d4e3..fafea29dd9 100644 --- a/libraries/Wire/src/Wire.h +++ b/libraries/Wire/src/Wire.h @@ -78,6 +78,7 @@ class TwoWire : public Stream { public: TwoWire(); TwoWire(uint32_t sda, uint32_t scl); + ~TwoWire(); // setSCL/SDA have to be called before begin() void setSCL(uint32_t scl) {