难以找出这种分段错误

时间:2013-04-02 23:01:34

标签: c debugging segmentation-fault

我确定错误是显而易见的,但我确实无法找到它。

基本上我试图通过2D阵列制作棋盘。我正在通过8个皇后测试测试它的功能......它不起作用。

不知何故,我的一个整数值正在逐渐消失,正如gdb所示:

....
(gdb) cont
Continuing.

Program received signal SIGSEGV, Segmentation fault.
0x080487f8 in diagnols (PARAMETER_ONE=0, PARAMETER_TWO=0) at eq1.c:77
77            if (key->board[abc][bcd] == 1) {
(gdb) print abc
4424  // "SHOULD BE" ONE
(gdb) print bcd
4424  // "SHOULD BE" ONE
(gdb) backtrace
#0  0x080487f8 in diagnols (PARAMETER_ONE=0, PARAMETER_TWO=0) at eq1.c:77
#1  0x08048873 in check (param1=0, param2=0) at eq1.c:91
#2  0x08048510 in recur (DEPTH=0, WIDTH=0) at eq1.c:99
#3  0x08048919 in main () at eq1.c:152
(gdb) 

然后这里是diagnols(...),它位于:

int recur(struct chessboard* key, int DEPTH, int WIDTH) {
    /* other functions above diagnols(...) */

diagnols(...):

int diagnols(int PARAMETER_ONE, int PARAMETER_TWO) { // returns 0 if good    

    int abc = 0;
    int bcd = 0;
    int counter = 0; // keeps track of conflicting piece occurrences 

    // OTHER CHECKS FIRST... DELETED TO SAVE ROOM

    // checkign diagnol down and to the left
    abc = PARAMETER_ONE+1;
    bcd = PARAMETER_TWO-1;
    while (  (abc>=0)&&(bcd>=0)  ) {
      if (key->board[abc][bcd] == 1) {
        counter++;
      } abc++;
      bcd--;
    }

    // ERROR IN THIS PART
    // checking diagnol down and to the right
    abc = PARAMETER_ONE+1;
    bcd = PARAMETER_TWO+1;
    while (  (abc>=0)&&(bcd>=0)  ) {
      if (key->board[abc][bcd] == 1) { // ERROR
        counter++;
      } abc++;
      bcd++;
    }

    return counter;
  }

diagnols(...)在以下函数的recur(...)中调用:

  int check(int param1, int param2) { // if okay returns 2 
    // other functions
    d = diagnols(param1, param2);
    int total = 0;
    total = (h + v + d); // if okay, equals 2
    return total;
  }

为了更好的衡量,这是我的结构:

struct chessboard {
  int board[7][7];
};

主要:

int main() {
  struct chessboard* master = malloc(sizeof(struct chessboard));
  /* i set the board to zero here. used calloc() before */
  recur(master, 0, 0);
  // stuff
}

是的,我知道 diagnol 没有拼写对角线;)

1 个答案:

答案 0 :(得分:2)

while (  (abc>=0)&&(bcd>=0)  ) {
      if (key->board[abc][bcd] == 1) { // ERROR
        counter++;
      } abc++;
      bcd++;
    }

由于您正在增加两个索引,因此条件似乎始终为真。

你的意思是<一些限制呢?