gpt4 book ai didi

c - 在用 C 编写的 DL 列表中出现段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 04:44:58 24 4
gpt4 key购买 nike

我试图在 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);
}

最佳答案

当程序试图用一个不存在的值做某事时,就会导致段错误,例如测试一个已经初始化但没有赋值的变量。编译器不会捕获段错误,这使它们成为最丑陋的错误。

我看到您能够使用 cur->next != NULL 行,它通常用于通过确保变量具有值来防止段错误。尝试使用诸如 if(cur != NULL) 之类的行来防止代码出现 fatal error 。

我还建议使用 gdb 调试器,它可以让您逐行检查代码并检查潜在问题。

关于c - 在用 C 编写的 DL 列表中出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22133677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com