[英]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.