Katelyn
Katelyn

Reputation: 121

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).

Upvotes: 1

Views: 442

Answers (1)

Hatted Rooster
Hatted Rooster

Reputation: 36463

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.

Upvotes: 7

Related Questions