2014-10-16 28 views
0

所以我試圖防止在下面的代碼中發生的段錯誤。這是發生的,因爲我試圖訪問列表中尚不存在的下一個元素。我如何防止這種情況?我如何檢查列表中的下一個元素是不是越界?

while (vm->item_list.head->data !=NULL) { 

    printf("%-10s",vm->item_list.head->data->id); 

    printf("%-20s",vm->item_list.head->data->name); 

    printf("%-70s",vm->item_list.head->data->description); 

    printf("%-15d",vm->item_list.head->data->on_hand); 

    printf("%s","$"); 
    printf("%d",vm->item_list.head->data->price.dollars); 
    printf("%s","."); 
    printf("%02d",vm->item_list.head->data->price.cents); 
    printf("\n"); 
    vm->item_list.head = vm->item_list.head->next; 

} 
printf("\n"); 
} 
+0

我希望鏈表有頭有臉的地方指針*除了*'這個結構vm' ,因爲如果不是這個循環保證泄漏/孤立整個列表,將'item_list.head'成員留空,然後立即進行segfaulting。 (這很可能是問題的核心)。在調試器中運行此代碼並逐步完成代碼。 – WhozCraig 2014-10-16 15:02:56

回答

1

使用類似while ((vm->item_list.head != NULL) && (vm->item_list.head->data !=NULL))

+0

由於某些原因,這仍然是斷層... – 2014-10-16 15:01:14

+0

'vm'分配正確嗎? – 2014-10-16 15:02:27

+0

...以及vm-> item_list? – 2014-10-16 15:33:49

0

在列表的初始化階段,你有你的下一個指針聲明列表的末尾,在這種情況下,NULL。如果你這樣做,比你確保這個指針不指向一個未定義的區域。 所以比你可以檢查這樣的:

while (vm->item_list.head->data !=NULL) { 

    printf("%-10s",vm->item_list.head->data->id); 

    printf("%-20s",vm->item_list.head->data->name); 

    printf("%-70s",vm->item_list.head->data->description); 

    printf("%-15d",vm->item_list.head->data->on_hand); 

    printf("%s","$"); 
    printf("%d",vm->item_list.head->data->price.dollars); 
    printf("%s","."); 
    printf("%02d",vm->item_list.head->data->price.cents); 
    printf("\n"); 

    if(vm->item_list.head->next != NULL){ 
     vm->item_list.head = vm->item_list.head->next; 
    }else{ 
     break; 
    } 

} 

或者你也可以做這樣的:

ItemNode* node = vm->item_list.head; 
while (node->data !=NULL || node->next != NULL) { 

    printf("%-10s",node->data->id); 

    printf("%-20s",node->data->name); 

    printf("%-70s",node->data->description); 

    printf("%-15d",node->data->on_hand); 

    printf("%s","$"); 
    printf("%d",node->data->price.dollars); 
    printf("%s","."); 
    printf("%02d",node->data->price.cents); 
    printf("\n"); 

    node = node->next; 
} 
相關問題