我正试图在C中实现DLlist,当我向列表中添加第二项时,我正在分段。。(int main的最后一行)。这是我第一次用C语言写作,通常我使用C++,所以我可能做了一些明显错误的事情,但我并不知道。如果你看到我做错了什么,请告诉我。谢谢
#include "schedule.h"
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
struct node *previous;
};
int listSize = 0;
struct node *head;
struct node *tail;
struct node *cur;
/*
* Function to add a process to the scheduler
* @Param tid - the ID for the process/thread to be added to the
* scheduler queue
* @return true/false response for if the addition was successful
*/
int addProcess(int tid){
if(tid)
{
cur->value = tid;
if(listSize == 0)
{
cur->next = (struct node *) malloc( sizeof(struct node));
cur->next->previous = cur;
head = cur;
tail = cur;
}
else
{
cur->next = (struct node *) malloc( sizeof(struct node));
cur->next->previous = cur;
}
cur = cur->next;
listSize++;
return 1;
}
return 0;
}
/*
* Function to remove a process from the scheduler queue
* @Param tid - the ID for the process/thread to be removed from the
* scheduler queue
* @Return true/false response for if the removal was successful
*/
int removeProcess(int tid)
{
cur = head;
// handles list size of 1 removal
if(cur == tail)
{
if(cur->value == tid)
{
free(cur->next);
cur->next = NULL;
free(cur);
cur = NULL;
listSize--;
return 1;
}
}
// handles removal of the head node
else if(head->value == tid)
{
cur->next->previous = NULL;
head = cur->next;
free(cur);
listSize--;
return 1;
}
else
// all other cases
while(cur->next != NULL)
{
// removal of a node with a next and a previous node
if(cur->value == tid)
{
cur->previous->next = cur->next;
cur->next->previous = cur->previous;
free(cur);
cur = NULL;
listSize--;
return 1;
}
// removal of the tail
else if(cur->next == tail)
{
if(tail->value == tid)
{
free(cur->next);
cur->next = (struct node *) malloc( sizeof(struct node));
listSize--;
return 1;
}
}
cur = cur->next;
}
return 0;
}
/*
* Function to get the next process from the scheduler
* @Return returns the thread id of the next process that should be
* executed, returns -1 if there are no processes
*/
int nextProcess(){
if(cur)
{
cur = cur->next;
return cur->previous->value;
}
return -1;
}
int main()
{
cur = head = tail = (struct node *) malloc( sizeof(struct node));
addProcess(5);
while(cur)
{
printf("%d ", cur->value);
cur=cur->next;
}
printf("n");
removeProcess(5);
addProcess(5);
}
当程序试图用不存在的值执行某些操作时,例如测试已初始化但未给定值的变量时,会导致分段错误。编译器不会发现seg错误,使它们成为最丑陋的错误。
我看到您能够使用cur->next != NULL
行,它通常用于通过确保变量有值来防止seg故障。尝试使用if(cur != NULL)
之类的行来防止代码出现致命错误。
我还建议使用gdb调试器,它将允许您逐行遍历代码并检查潜在的问题。