-1

When I compile my program, it displays

segmentaion fault (or) segmentation fault(core dumped)

My code seems to be working sometimes it gives the number of knight moves on the whole chessBoard, when moved on a square randomly chosen from all other paths, possibly a knight can take,but this doesn't seem to work always(just for simplicity,I have taken 5x5 chessboard ), why is this happening,what can i do to fix it?

#include <iostream>
#include <array>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
     array<array<int , 5>,5> chessBoard = {};
     array<int , 8> horizontal = {2,1,-1,-2,-2,-1,1,2};
     array<int , 8> vertical = {-1,-2,-2,-1,1,2,2,1};
     array<int, 8> temp ={};
     int count = 0 , t = 0 ,index;
     int cR = 4 , cC = 4 ,square =  1;
     srand(static_cast<unsigned>(time(0)));

     do
     {
       t = 0;
       for(size_t i = 0;i < 8;i++ )
       {
          cR += vertical[i];
          cC += horizontal[i];

          if(cR > 0 && cR < 8 && cC > 0 && cC < 8 && chessBoard[cR][cC] != -1)
          {
             temp[t] = i;
             t++;

          }
          cR -= vertical[i];
          cC -= horizontal[i];

       }
       if(t > 0)
       {
         index = rand() % t;
         chessBoard[cR][cC] = -1;
         cR += vertical[temp[index]];
         cC += horizontal[temp[index]];
         count++;
       }

       for(size_t j=0;j< t;j++)
         temp[j] = 0;

       square++;
   }while(square <= 25);

    cout<<"count is "<<count;
    return 0;

}

The error is Segmentation fault or sometimes it displays Segmentation fault (core dumped),what is wrong?

Tejendra
  • 1,874
  • 1
  • 20
  • 32
Afrah mohd
  • 21
  • 5
  • 5
    You did something wrong with a pointer. Possibly because you declared your chess board with a size of only 5x5 but you are comparing row and column against `8`. – Ben Voigt May 30 '19 at 05:16
  • You are accessing negative indices: cR += vertical[i]; cC += horizontal[i]; – Sumeet May 30 '19 at 05:19
  • 2
    Just a side note. Please double check when exactly the segfault occurs, it is very important information. If you compile your program and get a segfault then you have done something seriously wrong to a correct compiler or have a faulty compiler - more wrong that is possible with any kind of code, be it as weird and broken as it may be. But I bet that you do not get the segfault before you actually execute your own program, i.e. the result of compiling and otherwise building your code. – Yunnosch May 30 '19 at 07:09

1 Answers1

1

Replace

array<array<int , 5>,5> chessBoard = {};

by

array<array<int,8>,8> chessBoard;

A segmentation fault is when your program tries to access memory that it's not allowed to.

This does not happen when you compile, but when you run the program.

mfnx
  • 2,894
  • 1
  • 12
  • 28