Such things:
if (population[x-1][y-1] == true && x != 0 && y != 0)
need to rewrite as:
if ( x > 0 && y > 0 && population[x-1][y-1] == true )
otherwise, you will fall directly into the scope of undefined behavior if either x or y are 0 (since they will check_neighbors() several times when you call check_neighbors() from check_survivors() ), and you can expect strange, unexplained errors like this. Before attempting to access these elements, you need to check the invalid array indexes.
Also here:
if (neighbors < 2 || neighbors > 3) { //Neighbors less than 2 or more than 3 is dead cell survives = 0; } else if (neighbors == 3 && population[x][y] == false) { //Exactly 3 neighbors re-animates a cell survives = 1; } else if (population[x][y] == true) { //2 or 3 neighbors is survivor survives = 1; }
it seems that survives can be left with an undefined value if neighbors == 2 and population[x][y] == false , which will also lead to undefined behavior if you have to access this value. Itβs not immediately clear from your code whether there may be such a combination of circumstances, but if you are still at the debugging stage, then at least itβs worth adding a status check to check if it ever really is.
If your program exhibits undefined behavior like this, then it is almost impossible to explain until these problems are fixed.
Paul griffiths
source share