我很難在類項目的一段代碼中找到段錯誤(這部分未敘述)。我正在爲OS類實現一個隊列,並且在add函數中遇到了分段錯誤。C程序分段錯誤
void AddQueue(QElem * head, QElem * item) {
printf("WHERE\n");
if(head == NULL){
printf("THE\n");
head = item;
//item->next = item;
//item->prev = item;
}
else{
printf("$^&*\n");
(head->prev)->next = item;
printf("ARE\n");
item->prev = (head->prev);
printf("YOU\n");
item->next = head;
printf("FAILING\n");
head->prev = item;
}
printf("!?!?!?\n");
}
我有我從不同的類調用測試功能...
void TestAddQueue()
{
printf("********************************************\n");
printf("Begin testing the add test function\n");
printf("********************************************\n");
QElem * queue;
InitQueue(queue);
for(int i = 0; i < 10; i++)
{
printf("Adding element %d\n", i+1);
QElem * newElem = NewItem();
printf("Changing payload value\n");
newElem->payload = i+100;
printf("Adding to the queue\n");
AddQueue(queue, newElem);
printf("Item added, payload value = %d\n", queue->payload);
printf("The previous payload = %d\n", queue->prev->payload);
}
for(int i = 0; i < 10; i++)
{
printf("Rotating list", i+1);
RotateQ(queue);
printf("Printing element %d\n", i+1);
printQElem(queue);
}
}
這裏是的newitem功能...
QElem * NewItem()
{
// just return a new QElem struct pointer on the heap
QElem * newItem = calloc(1,sizeof(QElem));
newItem->next = newItem;
newItem->prev = newItem;
newItem->payload = -1;
return newItem;
}
...這裏是運行程序的輸出...
********************************************
Begin testing the add test function
********************************************
Adding element 1
Changing payload value
Adding to the queue
WHERE
THE
!?!?!?
Segmentation fault
現在,傳遞給add函數的頭指針應該是NULL,因爲它發送給初始化函數,它只是將指針的值設置爲NULL,所以我不認爲這會導致我的問題。
我的猜測是,下面一行是一個導致了問題...
printf("Item added, payload value = %d\n", queue->payload);
也許當我嘗試獲得有效載荷值,無論是我試圖訪問該結構已不存在或不知怎的,隊列指針被移動到一個無效的空間。任何反饋或在正確的方向推動將不勝感激。
注意:這是在Unix服務器環境(bash)中編譯的,此刻我無法訪問IDE來調試和查看變量。
有你的例子中缺少很多代碼;例如NewItem()。也就是說,我說:看看AddItem中的「(head-> prev) - > next」行:你已經檢查過「head」是非NULL,但沒有檢查到「head-> prev」 NULL – haavee 2015-02-12 09:06:06