gpt4 book ai didi

C - 段错误 - 链表的 insert_sort 函数

转载 作者:行者123 更新时间:2023-11-30 19:33:40 24 4
gpt4 key购买 nike

应用我在 Google 获得的一些排序方法 ( http://teknosrc.com/linked-list-in-c-insertion-sort/ ) 后,我的插入函数不起作用。

首先,我要使用的结构:

// This is the Node , where will be stored the item  

struct no
{
Item * item;
struct no *prox;
};
typedef struct no No;

//This is the list, where will have the head node(No)

struct lista
{
char *nomeLista; //This is just a name of the list
No *cabeca; //This is the head node
int tamanho; //This is the amount of items inserted (forgot to implement this)
struct lista *prox; //This is the next list
};
typedef struct lista Lista;

//This is just the main list that will guard all the list of nodes in a linked way. No need to worry about this.

struct vetorListas
{
Lista *cabeca; //head list
int tamanho; //amount of lists
};
typedef struct vetorListas VetorListas;

//This is the item to be inserted

struct item
{
int id; //the ID used for the comparison of sort
char *nome; //just the name of it
};
typedef struct item Item;

在此函数中,nomeDaList 是一个字符串 (char *),用于通过其他函数查找列表,iItem:

void *  
insert(void * nomeDaLista, Item * i)
{
Lista * auxLista; //the list
auxLista = idl(nomeDaLista); //the function to get the list by it's name. It works, no worries.


//down here, is the sequence of codes translated to my program (got by the website I showed before)

No * temp = auxLista->cabeca;
No * prev = NULL;
No * ptr;

Item * itemTemp;
itemTemp = temp->item;

ptr = criaNo(i); //this function creates (makes the malloc and all) a node (No) and return the created node.



if(temp == NULL)
{
ptr->prox=NULL;
auxLista->cabeca = ptr;
return auxLista;
}

if(i->id < itemTemp->id)
{
ptr->prox = auxLista->cabeca;
auxLista->cabeca = ptr;
return auxLista;
} else
{
while(temp != NULL)
{
if(i->id > itemTemp->id)
{
prev = temp;
temp = temp->prox;
continue;
} else
{
prev->prox = ptr;
ptr->prox = temp;
return auxLista;
}
}

prev->prox = ptr;
}
}

请帮助解决此段错误(核心转储)。

最佳答案

您在此行有一张支票
if(temp == NULL)
这应该而且通常会保护您免受通过 NULL 指针访问时出现的段错误。
然而,在几行之前,您已经两次取消引用未经检查的 temp
itemTemp = temp->item;

否 * temp = auxLista->cabeca;

您应该更改代码以确保仅在 tmp 为非 NULL 时才执行这些行。例如。拆分变量定义及其初始化并将 init 移至检查行之后。

您还可以从函数 criaNo(i) 接收一个指针,并在几行后使用它,而不检查它是否为 NULL。
ptr->prox=NULL;
目前尚不清楚是否保证为非 NULL。您必须“橡皮鸭”该函数,即详细检查它是否可以返回 NULL。

这是关于如何在没有调试器的情况下进行调试(大部分)的很好的描述,还解释了“橡皮鸭”。 https://ericlippert.com/2014/03/05/how-to-debug-small-programs/

对于您不知道如何使用调试器的问题:
How to debug using gdb?

对于您不使用IDE的问题:
找到一个,省去痛苦。
我最喜欢的搜索引擎将我当前使用的免费 IDE(“免费 IDE c”)作为第一个匹配项,我正在考虑切换到第三个匹配项。

关于C - 段错误 - 链表的 insert_sort 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45122746/

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