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. 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.
}
When you assign to a
MyStructthere is first an attempt to destroy the old members of the struct – but there isn’t any, because they were never constructed. Boom!
The easiest way to get a hundred
MyStructs is to use another vectorNo need to use
malloc.