samedi 28 janvier 2023

C++ local static std::vector with initial value undefined behavior

In my project, part of code behavior like undefined behavior. It have correctly worked been awhile(six months), our team and test engineers doesn't reported any bug until a few day ago. A few day ago when i was making some test, the code run weird, after some debug step we found a function that behave unexpected. Also i run the same code different machine but we didn't observe anomaly.

enum class eQtnIfacePort : uint16_t {
    ETH1_1 = 0x0,
    WIFI0_0 = 0x2,
    L_HOST = 0x3,
    ETH1_0 = 0x8,
    WIFI2_0 = 0xb,
    DROP = 0x1f,
};

bool check_msg(eQtnIfacePort msg) {

    static std::vector<eQtnIfacePort> v{eQtnIfacePort::ETH1_1, eQtnIfacePort::WIFI0_0};

    for(auto &i : v) {
        std::cout << "vector item: " << static_cast<int>(i) << "\n";
        if (msg == i)
            return true;
    }

    return false;
}

Debug output of the above code only be "vector item: 0" or "vector item: 2", but i saw random numbers like 3451, 2348 which are not defined in eQtnIfacePort enum.

What am i doing wrong, is there compiler bug or missing c++ knowledge?

compiler option Os, -std=c++11 compiler version gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0 tested machine ubuntu 20.04

Please don't suggest like use const static std::array or anything else. I wonder cause of problem.

Aucun commentaire:

Enregistrer un commentaire