【问题标题】:dynamic allocation and destruction of an array in a class类中数组的动态分配和销毁
【发布时间】:2014-05-01 18:21:05
【问题描述】:

我正在尝试用 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' 中的错误:双重释放或损坏(!prev):0x0000000001b26070 * [1] 4582 分段错误(核心转储)./gol

如果我注释掉以下几行,那么一切正常...:

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

谢谢

编辑:感谢 cmets,我用一个最小的非工作示例编辑了帖子并指出了问题,但是,我仍然不明白。

【问题讨论】:

  • 没有理由在 C++ 中使用new[]。动态数组是一个错误的特性,它从来都不是优雅的,而且经常是错误的。改用理智的东西。
  • 我非常同意@KerrekSB,而且我运行你的代码 GCC 4.7.2 并且运行良好。
  • 检查您是否在World::evolve()World::draw_text() 中搞砸了。
  • 我认为@Napseis 为使用动态数组提供了一个很好的理由:“了解幕后发生的事情”。这不是您在生产代码中会做的事情,但如果您想了解 C/C++ 的工作原理,那么了解内存管理问题很重要。
  • 我在构造函数或析构函数中没有看到会导致您看到的错误的错误——问题可能在于您没有提供的代码。但是请注意,通常最好不要在构造函数中进行以用户为中心的输入。首先获取并验证值,然后然后调用构造函数。

标签: c++ arrays dynamic-allocation


【解决方案1】:

好的,我发现了问题。 '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; 
    }
}

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

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2020-01-10
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    相关资源
    最近更新 更多