繁体   English   中英

分段错误?

[英]A segmentation fault?

我目前正在为学校开展这个项目,在那里我正在实施一种算法来找到“骑士游戏”的解决方案(这是关于找到从棋盘左上角到右下角的最短路径),但我三天来一直出现这个分段错误,我检查了我使用的每个指针,一切似乎都正确。 我实现了“搜索算法,bfs 和 dfs 和 ucs,前两个工作正常,但 ucs 给了我分段错误,即使它们使用相同的东西,除了 popBest 函数。以下是 ucs 和 popBest 函数的一些图片:

Item *popBest( list_t *list ) // and remove the best board from the list.
{
  assert(list);
  assert(list->numElements);

  int min_f;

  Item *item = list->first;
  Item *best;
  min_f = list->first->f;

  while (item) {
    if (item->f < min_f) {
      min_f = item->f;
      best = item;
    }
    item = item->next;
  }
  //item = onList(list, board);
  delList(list, best);

  return best;
}

void ucs(void)
{
    Item *cur_node, *child_p, *temp;

    while ( listCount(&openList_p) ) { /* While items are on the open list 
        printLt(openList_p );
        /* Get the first item on the open list*/
        cur_node = popBest(&openList_p);
        //printf("%d  %f\n", listCount(&openList_p), evaluateBoard( cur_node ));
        printBoard(cur_node);

        addFirst(&closedList_p, cur_node);

        if ( evaluateBoard(cur_node) == 0.0 ) {
            showSolution(cur_node);
            printf("\nParcours en largeur (bfs)\n" );
            return;
       }
       else {
            for (int i = 0; i < MAX_BOARD; i++) {
                child_p = getChildBoard( cur_node, i );

                if (child_p != NULL) {
                    child_p->f = cur_node->f+1;
                    temp = onList(&openList_p, child_p->board);
                    if (temp ==NULL) addLast( &openList_p, temp);
                    else if (temp != NULL && child_p->f < temp->f )
                    {
                        delList(&openList_p, temp);
                        addLast( &openList_p, temp);
                    }
                  }
                }
            }
        }

    return;
}

bfs 和 dfs 的所有函数都可以正常工作,唯一的区别是 popBest 函数。

你做list->first->f而不检查list->first是否是空指针。

您的问题的原因可能是best在循环后可能未初始化,如果列表中的第一个元素是“best”,那肯定是这样。

这是一个更安全的版本。

Item *popBest( list_t *list )
{
  assert(list);
  assert(list->numElements);
  assert(list->first);

  // Assume that the first element is best.
  Item *best = list->first;
  int min_f = best->f;

  // Search from the second element (if it exists).
  Item* item = best->next;
  while (item) {
    if (item->f < min_f) {
      min_f = item->f;
      best = item;
    }
    item = item->next;
  }
  delList(list, best);
  return best;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM