I'm trying to implement a game of life program in C++. I wish to resort only to basic tools, ie no vector whatsoever, in order to understand what is going on behind the scene.
I have a world class, like this:
class World
{
private:
int size[2];
int flat_size;
int *pop_n;
public:
World();
virtual ~World();
};
In the constructor, I ask for the world size and create the population array:
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;
}
I thought that I had to free the two arrays pop_n and pop_np1 in the destructor, so I wrote:
World::~World(){
delete [] pop_n;
cout << "A world has died" << endl;
}
The main is:
int main()
{
cout << "Hello Cthulhu!" << endl;
World sekai;
return 0;
}
but I get this error: Error in `./gol': double free or corruption (!prev): 0x0000000001b26070 * [1] 4582 segmentation fault (core dumped) ./gol
If i comment out the following lines, then every thing works fine...:
for (int i = 0; i < size[0]; i++){
for (int j = 0; j < size[1]; j++){
pop_n[ size[0] * i + j ] = rand() % 2;
}
}
Thanks
edit: Thanks to the comments, I edited the post with a minimal non working example and pin pointed the problem, that , however, I still don't understand.