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