动态分配和销毁类中的数组

时间:2014-05-01 18:21:06

标签: c++ arrays dynamic-allocation

我试图用C ++实现一个生命游戏程序。我希望只使用基本工具,即没有任何矢量,以便了解幕后发生的事情。

我有一个世界级的,像这样:

class World
{
private:
    int size[2];
    int flat_size;
    int *pop_n;
public:
    World();
    virtual ~World();
};

在构造函数中,我要求世界大小并创建种群数组:

World::World(){
int counter = 0;
int n = 0;
string size_string;

cout << "Please give world size, as 'width height':";
getline(cin, size_string );
istringstream size_string_s(size_string); 
while (size_string_s >> n ){
    size[counter] = n;
    counter++;
}

flat_size = size[0]*size[1];
pop_n = new int[ flat_size ];

// initialize seed for rand
srand (time(NULL));

for (int i = 0; i < size[0]; i++){
    for (int j = 0; j < size[1]; j++){
        pop_n[ size[0] * i + j ] = rand() % 2;  
    }
}

cout << "A world is born" << endl;
}

我以为我必须在析构函数中释放两个数组pop_n和pop_np1,所以我写道:

World::~World(){
delete [] pop_n;
cout << "A world has died" << endl;
}

主要是:

int main()
{
cout << "Hello Cthulhu!" << endl;
World sekai;

return 0;
}

但我收到此错误:     `./gol' ;: double free或corruption(!prev)出错:0x0000000001b26070 * [1] 4582分段错误(核心转储)./ gold

如果我注释掉以下几行,那么每件事情都可以......

for (int i = 0; i < size[0]; i++){
    for (int j = 0; j < size[1]; j++){
        pop_n[ size[0] * i + j ] = rand() % 2;  
    }
}

由于

编辑:感谢评论,我用最小的非工作示例编辑了帖子,并指出了问题,然而,我仍然不理解。

1 个答案:

答案 0 :(得分:0)

好的,我发现了问题。 'pop_n [size [0] * i + j]'中的索引不正确。 正确的循环是:

for (int l = 0; l < size[1]; l++){
    for (int c = 0; c < size[0]; c++){
        pop_n[ size[0] * l + c ] = 1;//rand() % 2;  
        nbn[ size[0] * l + c ] = 0; 
    }
}

我仍然想知道为什么删除失败了。