为什么delete []会使此测试程序崩溃

时间:2016-12-10 17:55:29

标签: c++ new-operator delete-operator

我声明了一个 new 指针数组。 我的问题是:为什么用delete[]删除数组导致程序崩溃?示例代码:

#include <iostream>

using namespace std;

typedef unsigned int uint32;

struct demon{
    private:
    static uint32 next_id;
    public:
    uint32 id;
    demon(){
        id = demon::next_id;
        demon::next_id++;
    }
};

uint32 demon::next_id = 1;

int main(){
    demon** demons = new demon*[5];
    demon d1;
    demon d2;
    demon d3;
    demon d4;
    demon d5;

    demons[1] = &d1;
    demons[2] = &d2;
    demons[3] = &d3;
    demons[4] = &d4;
    demons[5] = &d5;

    cout << demons[1]->id << endl;
    cout << demons[2]->id << endl;
    cout << demons[3]->id << endl;
    cout << demons[4]->id << endl;
    cout << demons[5]->id << endl;

    delete[] demons; // without this, the code works
    return 0;
}
*** Error in `./test': free(): invalid next size (fast): 0x0000000000e68c20 ***
Aborted

我测试了内存泄漏,没有删除,程序会出现段错误。

1 个答案:

答案 0 :(得分:2)

In C++ containers (arrays/vectors) use zero-based numbering.你应该使用:

demons[0] = &d1;
demons[1] = &d2;
demons[2] = &d3;
demons[3] = &d4;
demons[4] = &d5;

就像现在一样,您正在写入未分配的内存区域。这是极其复杂的错误场景的常见来源,因此您应该熟悉valgrind