Bizzare behaviour - local vs. global (Solved)

Dear community,

can anyone explain to me what could possibly be the reason for this bizarre behavior in the sketch below?

If I enable the "Global" "char TemperatureTextC[6] = {0};" then the counter does NOT increment.

However, If I enable(declare?) it in the "local" loop, it does indeed increment.

I'm not a programmer and "just" a Diesel mechanic therefore my understanding of C++ is equivalent to an amoeba I guess :o (So is my programming skill)

Here's the code that does NOT work:

float Celcius = 55.55;
char TemperatureTextC[6] = {0}; // If LOCAL - does work
long counter = 0;
void setup() {
  Serial.begin(115200);
}
void loop() {
  static unsigned long Timer1 = 0; 
  unsigned long Interval1 = 1000; // every 1 second(s)
  if (millis() - Timer1 >= Interval1) {
    Timer1 = millis();
    counter = counter + 1;
    Serial.println(counter);
    //char TemperatureTextC[6] = {0}; // If GLOBAL - does not work
    dtostrf(Celcius, 6, 2, &TemperatureTextC[0]);//  dtostrf(val, width, precision, TemperatureTextC
  }
}

And here the code that DOES work:

float Celcius = 55.55;
//char TemperatureTextC[6] = {0}; // If LOCAL - does work
long counter = 0;
void setup() {
  Serial.begin(115200);
}
void loop() {
  static unsigned long Timer1 = 0; 
  unsigned long Interval1 = 1000; // every 1 second(s)
  if (millis() - Timer1 >= Interval1) {
    Timer1 = millis();
    counter = counter + 1;
    Serial.println(counter);
    char TemperatureTextC[6] = {0}; // If GLOBAL - does not work
    dtostrf(Celcius, 6, 2, &TemperatureTextC[0]);//  dtostrf(val, width, precision, TemperatureTextC
  }
}

Any insight is highly appreciated

(Solved)

There is no room for the closing zero byte in a six byte buffer and a six byte char value,
so if directly adjacent in memory the next variable (counter?) gets overwritten with a zero byte.

   char TemperatureTextC[6] = {0};
    dtostrf(Celcius, 6, 2, &TemperatureTextC[0]);

Check what the second parameter of dtostrf() should be. It should not include the terminating zero on the string which will be added automatically by the compiler.

By using a value of 6 the compiler helpfully writes the terminating 0 to element 6 of the array which does not exist and stomps on memory containing who know what.

Uh Duuuuh! :slight_smile: :slight_smile: :slight_smile:

THANK YOU so much guys! Geee... me and Strings and char and friggin small strings don't sit around the same fire! I now remember something about the "terminating" 0.

I just changed the "Global" array to "[7]" and voila! it works perfect.

Many Thanks again for sharing your knowledge and plenty of digital Beer to you all.