相关疑难解决方法(0)

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

为什么会崩溃?我确实发现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 …
Run Code Online (Sandbox Code Playgroud)

c++ malloc stdvector visual-c++

0
推荐指数
1
解决办法
1379
查看次数

标签 统计

c++ ×1

malloc ×1

stdvector ×1

visual-c++ ×1