Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wire memory leak on multiple begin() call #2441

Closed
benmalenfant opened this issue Jul 16, 2024 · 2 comments · Fixed by #2442
Closed

Wire memory leak on multiple begin() call #2441

benmalenfant opened this issue Jul 16, 2024 · 2 comments · Fixed by #2442

Comments

@benmalenfant
Copy link
Contributor

benmalenfant commented Jul 16, 2024

Describe the bug
When calling begin() after the receive and transmit buffers have been allocated, the begin function orphans the allocations by resetting the pointer to nullptr, on the next call of allocateTxBuffer(), we get a new memory allocation while the previous one has never been freed, this in turns causes heap segmentation and will lead to lack of memory in the long run.

Proposed fix in #2442

To Reproduce
Using this simplified code, we can see that the Wire receive buffer is reallocated every requestFrom call

#include <Arduino.h>
#include <Wire.h>

void setup() {
}

void loop() {
  Wire.begin();
  Wire.requestFrom(1,1);
}

Steps to reproduce the behavior:

  1. Run demo code
  2. Place a breakpoint in allocateRxBuffer right after the realloc line
  3. Notice the tmp pointer increase location every call
  4. Wait long enough and you'll run out of memory

Expected behavior
The wire library should not cause a memory leak, even if calling begin() multiple times is bad practice.

Board (please complete the following information):

  • Name: BlackPill STM32F411CEU6
  • Hardware Revision: V3.1

Applicable to any stm32

@fpistm
Copy link
Member

fpistm commented Jul 16, 2024

Hi. In fact your code is wrong. You have to call Wire.end();
This is like you call malloc each loop iteration without calling free.

@benmalenfant
Copy link
Contributor Author

Yeah I agree, this is dummy code, but my philosophy is that Arduino should be dummy proof. This became an issue for me because I had locally scoped a sensor object(I know this was stupid...), destroying and creating it every time caused it to call begin and in turn cause the memory leak.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants