【发布时间】:2014-03-31 19:55:47
【问题描述】:
int main(int argc, char *argv[])
{
printf("successfully started main\n");
struct uf_list myList;
uf_list_allocate(&myList);
printf("successfully allocated myList\n");
insert_node(&myList, 'c');
printf("successfully inserted into myList\n");
return 0;
}
...
void uf_list_allocate(struct uf_list *list)
{
list = malloc(sizeof(struct uf_list));
if(list == NULL)
{fprintf(stderr, "no memory for allocate");}
list->head = list->tail = NULL;
}
//--------------------------------------------------------------------------------------
void insert_node(struct uf_list *list, const char label)
{
struct uf_node *it = malloc(sizeof(struct uf_node));
if(it == NULL)
{fprintf(stderr, "no memory for insert");}
it->c = label;
it->next = NULL;
it->rep = NULL;
if(list->head == NULL) //the list is empty
{ list->head = list->tail = it;}
else
{ list->tail->next = it; list->tail = it; }
it->rep = list->head;
}
/*----------------------------------------------------------------------------*/
struct uf_node
{
char c;
struct uf_node *next;
struct uf_node *rep;
};
/*----------------------------------------------------------------------------*/
struct uf_list
{
struct uf_node *head;
struct uf_node *tail;
};
当我尝试将一个元素从main 插入到我的列表中时,我遇到了分段错误。
是什么导致了分段错误?如果您需要更多信息,例如structs 的定义,请告诉我!
编辑:我意识到我做了什么。在allocate里面我改了局部变量list.的地址,这意味着myList什么都没有发生。但是,现在我遇到了以下难题:我将 myList 的声明放在 main, 之外,一切正常:
struct uf_list myList;
int main(int argc, char *argv[])
{
printf("successfully started main\n");
uf_list_allocate(&myList);
printf("successfully allocated myList\n");
insert_node(&myList, 'c');
insert_node(&myList, 'd');
insert_node(&myList, 'e');
printf("successfully inserted into myList\n");
print_uf_list(&myList);
return 0;
}
我不太明白为什么。似乎应该应用相同的逻辑,即,由于我将 myList 的地址传递给 allocate,然后更改局部变量 list 地址并对该地址进行操作,这如何反映在 myList 的内存地址上不是在操作吗?
【问题讨论】:
-
-1:你有 1.2k 的代表,当然你知道最好不要先做一些基本的调试就问一个关于 seg-fault 的问题。
-
我到处都放了一堆打印语句,但没有运气......我很少用 C 编程,我所做的大部分事情都是用高级语言编写的。这里的一切对我来说似乎都是合乎逻辑的。我不知道还能做什么......
-
单步执行,看看执行的最后一行可能是什么?列表结构的声明在哪里?问题很可能是从您没有发布的 uf_list_allocate() 开始的。
-
顺便说一句,如果 malloc 失败,代码不应继续。最佳口头禅...
-
是双向链表吧?所以
it->rep应该指向前一个节点而不是list->head?
标签: c linked-list segmentation-fault