Segmentation fault when inserting in a map

I want to add a new entry in a map, but I am getting a segmentation fault message.

class A {

}; 

class B {
public:
    std::map<int, std::vector<A*> > m;
};

int main() {
    A *a = (A*)malloc(sizeof(A));
    B *b = (B*)malloc(sizeof(B));
    b->m[0].push_back(a);
    return 0;
}

I am getting the error when I am doing b->m[0].push_back(a).

1 answer

  • answered 2018-01-11 20:15 Sombrero Chicken

    Never use malloc in C++, always use new.

    Because you're using malloc the constructor never gets called and thus your m is in an undefined state. Exhibiting undefined behavior when accessing it.

    Moreover, m is storing pointers to A, which means that the default-constructed element when accessing with [] is nullptr, even more UB.

    That said, actually never use raw new and just use scope based automatic lifetime or std::unique_ptr.