gpt4 book ai didi

c++ - 为什么 push_back() 会导致 malloc() 处理的数据崩溃?

转载 作者:太空宇宙 更新时间:2023-11-04 14:39:47 32 4
gpt4 key购买 nike

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

附言。我知道 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.
}

最佳答案

在行 array[0] = element; 中,您正在调用 array[0]operator=。由于 array[0] 未初始化,因此这是未定义的行为。在尚未调用其构造函数的对象上调用任何方法或运算符(包括 operator=)是未定义的行为。

要解决您的问题,您要么需要使用 placement new 来调用 array[0] 的构造函数,要么只使用 new 而不是 malloc 。除非您有充分的理由使用 malloc,否则后者更可取(甚至更好:使用 vector )。

关于c++ - 为什么 push_back() 会导致 malloc() 处理的数据崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10857402/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com