My first Segmentation Fault 11

Trying to write a Game of Life simulation. It is compiling, but on run throws Segmentation Fault 11. Any suggestions?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include<vector>
#include<unistd.h>
#include<cstdlib>
using namespace std;

#define ROWS 5
#define COLS 5

#define DEAD  ' '
#define ALIVE '*'

    vector< vector<char> > world(ROWS, vector<char>(COLS, DEAD));
    vector< vector<char> > world_copy(ROWS, vector<char>(COLS, DEAD));

    void generation(vector< vector<char> > &world, vector< vector<char> > &world_copy)
{
    // copy the contents of world into world_copy
int number;
    for(int i = 0; i < ROWS; i++) {
        for(int j = 0; j < COLS; j++) { 
             number==0;
             for(int x=i-1; x<=i+1; x++) {
                  for(int y=j-1; y<=j+1; y++) {
                        while((i!=x) || (j != y)) {
                            if((world_copy[x][y]) = ALIVE)
                            {
                                number++;
                            }
                            else{}
                        }}}
                    if(number==2){
                        world[i][j] = world_copy[i][j] = ALIVE;
                    }
                    else {(world[i][j]) = world_copy[i][j] = DEAD;}

        }
    }
}

    void display(vector< vector<char> > &world)
{
    // display the 2D matrix
    for(int i = 0; i < ROWS; i++)
        {
            for(int j = 0; j < COLS; j++)
            {
                cout << world[i][j];
            }
            cout << endl;
        }
}


int main()
{

    // set some cells of world to ALIVE for initial configuration
    world[3][2] = world[3][3] = world[3][4] = ALIVE;

    while(true)
    {
        // clear the screen and display the world
        system("clear");
        display(world); 
        // wait for some time
        usleep(800000); 
        generation(world, world_copy);
    }
    return 0;
}
Last edited on
You're stepping out of bounds of your vector.

1
2
// Line 23:
for(int x=i-1; x<=i+1; x++) {


x will be out of bounds when i==0 or when i==ROWS-1

Same problem with y on line 24
Thank you Disch! I changed lines 21 and 22 to
1
2
for(int i = 1; i <= ROWS; i++) {
        for(int j = 1; j <= COLS; j++) {

That solved my segmentation error.
Last edited on
You're still going out of bounds with that.

If x==i+1 and i==COLS, then x==COLS+1 which is out of bounds.
Topic archived. No new replies allowed.