1

Using a Teensy 3.2, my program is hanging at the section pointed out below. I don't know how to access glyph. I can see all lines print to my Arduino serial monitor if I comment out the //hangs here line.

#include <vector>
#include <Arduino.h>

class Letter {
    public:
        String glyph = "a";
};

class Language {
    public:
        Language();
        std::vector <Letter> alphabet;
};

Language::Language(){
    std::vector <Letter> alphabet;
    Letter symbol = Letter();
    alphabet.push_back(symbol);
    delay(2000);
    Serial.println("hello world");//prints in the arduino monitor
    Serial.println(this->alphabet[0].glyph);//hangs here
    Serial.println("line of interest executed");//runs only if line above is commented out
}

void setup() {
    Serial.begin(9600);
    Language english = Language();
}

void loop() {

}      
mh00h
  • 1,824
  • 3
  • 25
  • 45

1 Answers1

2

You're defining a local variable alphabet and push_back one element into it. This has nothing to do with the member variable alphabet. Then this->alphabet[0].glyph leads to UB, member variable alphabet is still empty.

You might want

Language::Language() {

    Letter symbol = Letter();
    this->alphabet.push_back(symbol);
    // or just alphabet.push_back(symbol); 

    delay(2000);
    Serial.println("hello world");//prints in the arduino monitor
    Serial.println(this->alphabet[0].glyph);
    Serial.println("line of interest executed");
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405