Skip to content

Commit ff1731f

Browse files
committed
fix(Wire): avoid memory leaks
add destructor to call end(). Fixes #2142 Signed-off-by: Frederic Pillon <[email protected]>
1 parent 471a0ea commit ff1731f

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

Diff for: libraries/Wire/src/Wire.cpp

+17-4
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,15 @@ TwoWire::TwoWire(uint32_t sda, uint32_t scl)
4545
_i2c.scl = digitalPinToPinName(scl);
4646
}
4747

48+
/**
49+
* @brief TwoWire destructor
50+
* @retval None
51+
*/
52+
TwoWire::~TwoWire()
53+
{
54+
end();
55+
}
56+
4857
// Public Methods //////////////////////////////////////////////////////////////
4958

5059
void TwoWire::begin(uint32_t sda, uint32_t scl)
@@ -106,11 +115,15 @@ void TwoWire::begin(int address, bool generalCall, bool NoStretchMode)
106115
void TwoWire::end(void)
107116
{
108117
i2c_deinit(&_i2c);
109-
free(txBuffer);
110-
txBuffer = nullptr;
118+
if (txBuffer != nullptr) {
119+
free(txBuffer);
120+
txBuffer = nullptr;
121+
}
111122
txBufferAllocated = 0;
112-
free(rxBuffer);
113-
rxBuffer = nullptr;
123+
if (rxBuffer != nullptr) {
124+
free(rxBuffer);
125+
rxBuffer = nullptr;
126+
}
114127
rxBufferAllocated = 0;
115128
}
116129

Diff for: libraries/Wire/src/Wire.h

+1
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ class TwoWire : public Stream {
7878
public:
7979
TwoWire();
8080
TwoWire(uint32_t sda, uint32_t scl);
81+
~TwoWire();
8182
// setSCL/SDA have to be called before begin()
8283
void setSCL(uint32_t scl)
8384
{

0 commit comments

Comments
 (0)