rjt197197
rjt197197

Reputation: 11

Segmentation fault accessing 2D array

I have a 2D array representing a sudoku grid defined like this:

int** sudoku = (int**)malloc(sizeof(int*) * 9);
for(i = 0; i < 9; i++)
    sudoku[i] = (int*)malloc(sizeof(int) * 9);

I've run it through a function that iterates through every element and prints, which works fine (displays 81 zeros). But then, I hand it to another function that reads a grid from a file into this array. Here's what it looks like (with a bunch of printf statements I'm using for debugging omitted).

void readSudokuFile(char* filename, int*** grid) {
    FILE* file;
    int i, j, curr;

    file = fopen(filename, "r");
    for(i = 0; i < 9; i++) {
        for(j = 0; j < 9; j++) {
            fscanf(file, "%d", &curr);
            *grid[i][j] = curr;
        }
    }
    fclose(file);
}

When the function is running, it appears to read find for the first row, but when it gets to the second row and tries to insert a value into sudoku[1][0], I get a seg fault. This is what the output looks like with my printfs in:

Reading line 0...
    Reading col 0... got 6
    Reading col 1... got 2
    Reading col 2... got 4
    Reading col 3... got 5
    Reading col 4... got 3
    Reading col 5... got 9
    Reading col 6... got 1
    Reading col 7... got 8
    Reading col 8... got 7
Reading line 1...
    Reading col 0... got 5
Segmentation fault(core dumped)

This is the file I'm trying to read in:

6 2 4 5 3 9 1 8 7
5 1 9 7 2 8 6 3 4
8 3 7 6 1 4 2 9 5
1 4 3 8 6 5 7 2 9
9 5 8 2 4 7 3 6 1
7 6 2 3 9 1 4 5 8
3 7 1 9 5 6 8 4 2
4 9 6 1 8 2 5 7 3
2 8 5 4 7 3 9 1 6

I'm compiling using gcc with -Wall and -pedantic, and am getting no compiler warnings.

I've googled around for a few hours to no avail, I'm not exactly sure what's going wrong here. Any help would be greatly appreciated.

Upvotes: 0

Views: 1026

Answers (2)

Anders Cedronius
Anders Cedronius

Reputation: 2076

To avoid pointer bugs you just ran into I suggest to simplify your dynamic 2D-array allocation like this ->

int (*array) [Y] = malloc(sizeof(int[X][Y]));

Access your array like this ->

int g=array[0][0];

And set like this ->

array[0][0]=0;

That will simplify your solution a lot and you also get a continuous memory block containing your 2D-array as a bonus. That will also simplify writing and reading files as you do not need to traverse each element if you do not necessarily have to do that for other reasons.

/A

Upvotes: 2

Tu.Ma.
Tu.Ma.

Reputation: 1395

Try modify your function like this:

        void readSudokuFile(char* filename, int** grid) {
   // ...
                grid[i][j] = curr;
    }

and invoke it like this:

readSudokuFile(filename, sudoku)

Upvotes: 1

Related Questions