I’m making terminal game of life and when glider figure goes out of the map segfault 11 appears. Could you tell me where particularly this segfault appears and how to solve it?
my main.cpp looks like that:
#include "src/Board.hpp"
int main(){
Board board(1);
while(!board.isOver()){
board.new_frame();
}
}
my Board.hpp looks like that:
#pragma once
#include <iostream>
#include <chrono>
#include <thread>
#define square_size 20
#define yMax square_size
#define xMax square_size * 5 / 2
class Board
{
private:
bool cells[yMax][xMax] = {{0}};
bool gameOver;
int frame;
public:
Board(){
setup();
}
Board(int n){
setup();
}
void setup(){
cells[10][10] = 1;
cells[10][11] = 1;
cells[10][9] = 1;
cells[11][11] = 1;
cells[12][10] = 1;
gameOver = 0;
frame = 1;
}
void screenClear(){
system("clear");
}
void wait(){
using namespace std::literals::chrono_literals;
std::this_thread::sleep_for(50ms);
}
int count_near(int y, int x){
int cnt = 0;
for (int i = -1; i < 2; i++){
for(int j = -1; j < 2; j++){
if (j!=0 || i != 0){
if (y + i < yMax && y + i >= 0 && x+j < xMax && x+j >= 0){
if (cells[y+i][x+j] == 1){
cnt++;
}
}
}
}
}
return cnt;
}
void output(int y, int x){
if (cells[y][x] == 1){
std::cout<<'*';
}else{
std::cout<<'.';
}
}
void new_frame(){
std::vector<int> changes;
screenClear();
for(int i = 0; i < yMax; i++){
for (int j = 0; j < xMax; j++){
output(i, j);
int cnt = count_near(i, j);
if (cells[i][j] == 1){
if (cnt < 2){
changes.push_back(i);
changes.push_back(j);
changes.push_back(0);
}else if (cnt > 3){
changes.push_back(i);
changes.push_back(j);
changes.push_back(0);
}
}else{
if (cnt == 3){
changes.push_back(i);
changes.push_back(j);
changes.push_back(1);
}
}
}
std::cout<<'n';
}
for (int i = 0; i < changes.size() - 2; i+=3){
if (changes[i+2] == 0){
cells[changes[i]][changes[i+1]] = 0;
}else{
cells[changes[i]][changes[i+1]] = 1;
}
}
std::cout<<frame<<std::endl;
frame++;
wait();
changes.clear();
}
void makeOver(){
gameOver = 1;
}
bool isOver(){
return gameOver;
}
};
I googled and found out that seg fault 11 means accessing the memory space it is not allowed to space however my count_near function checks if y is within range of 0 to yMax and x is within range of 0 to xMax and it still output segmentation fault when the glider goes out of the map.