为什么push_back()会导致malloc()的数据崩溃? [英] Why does push_back() cause crash within malloc()'ed data?

查看:170
本文介绍了为什么push_back()会导致malloc()的数据崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why does this crash? I did find out malloc() doesnt call constructors, so I called them myself manually, but it still crashes, I do not understand why.

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

PS. I know std::vector and new[] exists. Do not tell me to use vectors/new[] as an answer.

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

推荐答案

分配给MyStruct

array[0] = element;

首先尝试破坏结构的旧成员-但没有尝试,因为它们从未被构造.轰!

there is first an attempt to destroy the old members of the struct - but there isn't any, because they were never constructed. Boom!

获取一百个MyStruct的最简单方法是使用另一个向量

The easiest way to get a hundred MyStructs is to use another vector

vector<MyStruct>  v(100);

无需使用malloc.

这篇关于为什么push_back()会导致malloc()的数据崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆