Skip to content

Commit

Permalink
fix(Wire): avoid memory leaks
Browse files Browse the repository at this point in the history
add destructor to call end().
Fixes #2142

Signed-off-by: Frederic Pillon <[email protected]>
  • Loading branch information
fpistm committed Oct 19, 2023
1 parent 471a0ea commit ff1731f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
21 changes: 17 additions & 4 deletions libraries/Wire/src/Wire.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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;
}

Expand Down
1 change: 1 addition & 0 deletions libraries/Wire/src/Wire.h
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down

0 comments on commit ff1731f

Please sign in to comment.