【发布时间】:2015-02-12 09:02:13
【问题描述】:
我很难在类项目的一些代码中定位分段错误(这部分未分级)。我正在为一个 OS 类实现一个队列,并且在 add 函数中遇到了分段错误。
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”是否为非空
标签: c pointers segmentation-fault