Arduino program using i2c stops working after printing to OLED a few times A NOTE ON THE PROJECT AND PROGRAM STRUCTURE

I am developing an open source Smart Watch project using Arduino.
The code can be found here: https://github.com/shivangsgangadia/SmartWatch
The code is too large and divided into multiple files, hence I cannot paste it here within the question, hence I request you to look into the github repo.

So far I have interfaced an OLED (128 X 64 SSD1306) and RTC (DS3231 in ZS-042).
I have written libraries for both, which have been included in Github repo.

The program structure allows to add multiple "Modules" which are basically like apps. There is a static State class that holds the program state such as modules to be serviced, and time from RTC.
Each "Module" can be a "App" or "Overlay". Overlays are always visibles, there can be mutiple overlays active, but only 1 app can exist at a time.

WHAT I AM TRYING TO DO ?


Read RTC into State class's static variables
Display once
Attach interrupt to set boolean flag when the RTC gives interrupt (alarm
set to 1 minute) Service interrupt in loop by:


Read RTC into State class's static variables
Reset alarm for RTC
Update display



WHAT IS THE PROBLEM ?

The program works fine 2-3 times, i.e. does what's expected after servicing 2-3 interrupts (hence 2-3 minutes), but after that the print on the OLED becomes mangled and the program stops altogether.

WHAT HAVE I TRIED TO SOLVE IT ?

With Serial.println() in many areas such as before and after OLED::writeString is called in respective classes, I concluded that the RTC is not the issue, but the OLED somehow causes the program to stop.

Removing OLED::writeString statements does allow the rest of the printing to continue for more than 2-3 times, but the program eventually does stop. I have tried replacing the wires and the breadboard, but nothing seems to have any effect.
This is wrong in many ways:

String input = Serial.readString();
serialInputBuffer = new char[input.length()];
input.toCharArray(serialInputBuffer, input.length());


What's fatal is that you later don't free the memory allocated with new. Don't use String and new. Both use heap memory and will fragment it with these small allocations until there is no space for the next allocation. I see you have dynamic allocation in other parts of the sketch and there it looks like you have a delete, but they still cause the fragmentation problem.

Use a global buffer like char serialInputBuffer[64]; and use:

int l = Serial.readBytes(serialInputBuffer, sizeof(serialInputBuffer));
serialInputBuffer[l] = 0;


In the scale function, there is a dynamically allocated array. Replace it with a class variable, which acts as a buffer which can hold the maximum number of bytes you expect the use to scale their byte to.

Again, dynamic allocations will cause fragmentation even if the memory is released properly.