为什么push_back()会导致malloc()的ed数据崩溃?

Roo*_*kie 0 c++ malloc stdvector visual-c++

为什么会崩溃?我确实发现malloc()没有调用构造函数,所以我手动调用它们,但它仍然崩溃,我不明白为什么.

PS.我知道std :: vector和new []存在.不要告诉我使用vectors/new []作为答案.

struct MyStruct {
    vector<int> list;
};
void make_crash(){
    MyStruct *array = (MyStruct *)malloc(100*sizeof(MyStruct));
    MyStruct element; // initialize element here since malloc() doesnt do it.
    array[0] = element; // copy, everything should be alright?
    array[0].list.push_back(1337); // nope, BANG!
    // The above line makes these:
    // First-chance exception at 0x7c970441 in test.exe: 0xC0000005: Access violation reading location 0xbaadf005.
    // First-chance exception at 0x00401cd0 in test.exe: 0xC0000005: Access violation reading location 0xbaadf00d.
    // Unhandled exception at 0x00401cd0 in test.exe: 0xC0000005: Access violation reading location 0xbaadf00d.
}
Run Code Online (Sandbox Code Playgroud)

sep*_*p2k 7

上线array[0] = element;你调用operator=array[0].由于array[0]未初始化,这是未定义的行为.调用任何方法或运算符(包括operator=尚未调用其构造函数的对象)是未定义的行为.

要解决您的问题,您需要使用placement new来调用构造函数,array[0]或者只使用new而不是malloc.除非你有充分的理由使用malloc,否则后者是非常可取的(甚至更好:使用矢量).