为什么会崩溃?我确实发现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)