【发布时间】:2012-06-01 21:11:43
【问题描述】:
为什么会崩溃?我确实发现 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.
}
【问题讨论】:
-
为什么你想这样做?
-
@K-ballo,因为我很愚蠢...
-
如果我说我也是个白痴怎么办,我会加分吗? :P
-
虽然被误导了,但你的问题仍然很有趣......我只是想知道是什么让某人甚至尝试这样做。
-
@K-ballo,为什么?确实,确实……生命的奥秘。
标签: c++ visual-c++ malloc stdvector