c++arduinoteensy

cpp program hanging when accessing member variable of a class member


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() {

}      

Solution

  • 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");
    }