0

I'm a little lost. I've been trying to debug this segmentation fault for a few days now and still can't figure out what to do. I narrowed the problem down to a particular line of code thanks to a combination of debug50 and a printf command.

The code in question:

bool move(int tile)
{
     if (tile > d * d - 1 || tile < 1)
     {
        return false;
     }

     int r = 0;
     int c = 0;

     for (int r = 0; i < d; i++)
     {
        for (int c = 0; j < d; i++)
        {
            if (tile == board[i][j])
            {
                int blank = 0;
                if (((r == (i - 1)) && (c == j)) || ((r == (i + 1)) && (c == j)) ||
                ((r == i) && (c ==(j - 1))) || ((r == i) && (c == (j + 1))))
                {
                    board[r][c] = tile;
                    board[i][j] = blank;
                    r = i;
                    c = j;

                    return true;
                }
             }
         }
     }
     return false;
}

The segmentation fault appears to trigger when I call "if (tile == board[i][j])". For some reason or other, when I was using the debugger, it seems to think that the variable of "i" is a value of 3864 while the variable of "tile" is a value of 3. All other variables involved are at a value of 0.

I'm stumped by this. Can anyone point me in the right direction?

1
  • You don't seem to declare i and j at all, but r and c twice?
    – Blauelf
    Nov 10, 2017 at 18:59

1 Answer 1

0

Where are i and j declared and where are their values set???? For this to have actually run, it means that they must be global variables. This code is relying on something set somewhere else (i and j) that the local code has no control of.

This is an excellent example of why global variables should be avoided unless there is a really good reason for using them. Even if the use of globals is justified, they should have far more descriptive names than single letters, especially i and j. i an j are so commonly used in for loops that they should never be used as global var names.

It also looks like the usage of i,j,r, and c have been confused in the code, particularly the for loop setups.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

3
  • Just seen that I accidentally declared the r and c variables twice in the code while typing it >A<;;;;;;; I am going to check those i and j variables in the rest of the code and see if I've made a mistake somewhere along the line (knowing me, probably have). Thanks for the tip off. Nov 11, 2017 at 0:00
  • UPDATE: Upon further inspection, I realised the problem. Nov 11, 2017 at 0:10
  • "for (int j = 0; j < d; i++)" <----- I was being dopey Nov 11, 2017 at 0:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .