C++ int undefined behaviour when stored as RTC_NOINIT_ATTR (ESP32)

  arduino-esp32, c++, esp32

I’m programming an ESP32 using VSCode. I have the following simple script:

#include <Arduino.h>

RTC_DATA_ATTR int counter1 = 0;
RTC_NOINIT_ATTR int counter2 = 0;

void setup() {
Serial.begin(115200);
Serial.printf("RTC programme running, counter1 = %d; counter2 = %dn",counter1,counter2);
delay(3000);
counter1++;
counter2++;
esp_restart();
}

void loop() {
  // nothing needed here
}

I’d expect the output to be:

RTC programme running, counter1 = 0; counter2 = 0
RTC programme running, counter1 = 0; counter2 = 1
RTC programme running, counter1 = 0; counter2 = 2
...

But instead I’m getting:

RTC programme running, counter1 = 0; counter2 = 109811943
RTC programme running, counter1 = 0; counter2 = 109811944
RTC programme running, counter1 = 0; counter2 = 109811945
...

(where the value of counter2 is a random value). I’ve tried various combinations of int, uint32_t etc. but still get the random value. It’s caused by the RTC_NOINIT_ATTR definition but it’s what I need for the eventual application. Anything I can be doing differently?

Source: Windows Questions C++

LEAVE A COMMENT