[英]Linked List in C - Segmentation Fault
我是一个初学者,正在学习如何在C语言中创建链接列表。每当我尝试打印列表时,列表就可以很好地打印出来,但是最后我总是遇到分段错误。
当我使用GDB回溯时,它将指向行-> entry = *((* node).data); 在printContents函数中。
但是我不太确定这是怎么回事。
这是链接列表代码:
void createEmptyLinkedList(LinkedList *inList) {
inList = (LinkedList*)malloc(sizeof(LinkedList));
(*inList).head = NULL;
(*inList).tail = NULL;
(*inList).size = 0; //Keeps track of size of list
return;
}
void insertAtStart(LinkedList *inList, JournalEntry *inValue) {
LinkedListNode *newNode;
int listSize = (*inList).size;
newNode = (LinkedListNode*)malloc(sizeof(LinkedListNode));
(*newNode).data = inValue;
(*newNode).next = (*inList).head;
(*inList).head = newNode;
((*inList).size)++;
return;
}
void printContents(LinkedList *inList) {
LinkedListNode *node;
JournalEntry entry;
node = (*inList).head;
while (node != NULL) {
entry = *((*node).data);
printf("%04d-%02d-%02d: %s\n", entry.year, entry.month, entry.day, entry.text);
/*Move node to the next node*/
node = (*node).next;
}
printf("Done!");
return;
}
//Free nodes recursively
void freeLinkedList(LinkedList *inList) {
freeNode((*inList).head);
free(inList);
return;
}
void freeNode(LinkedListNode *node) {
if (node != NULL) {
freeNode((*node).next);
free(node);
}
这是用于启动链表的主要功能:
int main() {
LinkedList list;
JournalEntry *value;
char* textToEnter;
value = (JournalEntry*)malloc(sizeof(JournalEntry));
createEmptyLinkedList(&list);
textToEnter = "Hello";
(*value).day = 10;
(*value).month = 5;
(*value).year = 2010;
strcpy((*value).text, textToEnter);
insertAtStart(&list, value);
printContents(&list);
freeLinkedList(&list);
return 0;
}
万一有人需要它,以下是头文件中声明的结构:
typedef struct LinkedListNode {
JournalEntry *data;
struct LinkedListNode *next;
} LinkedListNode;
typedef struct {
LinkedListNode *head;
LinkedListNode *tail;
int size;
} LinkedList;
typedef struct {
int day;
int month;
int year;
char text[1000];
} JournalEntry;
C语言中的所有内容均按值传递,包括指针。 因此,分配给inList不会影响调用者已传递的值。 相反,如果您想以这种方式执行操作,则应该使用一个指向指针的指针:
void createEmptyLinkedList(LinkedList **inList) {
*inList = malloc(sizeof(LinkedList));
(*inList)->head = NULL;
(*inList)->tail = NULL;
(*inList)->size = 0; //Keeps track of size of list
return;
}
没有这个,您将只使用未初始化的指针来保存列表。 在您的主代码中,您还需要更改它,例如:
LinkedList *list;
createEmptyLinkedList(&list);
注意这里的列表被声明为指针。
从我的角度来看,问题是您没有决定createEmptyLinkedList()
是否应该为您的头部分配内存,或者您将在main()
函数中进行分配。
和你都做。
在main()
您做了LinkedList list;
-这部分创建LinkedList结构。
然后,您将该结构的地址传递给函数。 到目前为止,这很好。
在createEmptyLinkedList()
,有inList指针指向列表结构。 那也很好。
但是,现在您搞砸了,并使用malloc()
另一个LinkedList结构,使inList
指向新的malloc结构。
然后,您初始化了全新的LinkedList结构,从createEmptyLinkedList()
返回而不更改main()
list
结构,因为您初始化了新的malloc'd
结构, 而不是list 。
您可以通过确定是在main()
还是createEmptyLinkedList()
创建LinkedList
结构来修复它。
如果您选择第二-阅读以上答案。
但是,如果您选择1st,则保持原样,并删除createEmptyLinkedList()
中负责malloc分配的行。
然后,如FatalError建议的那样-您的函数更合适的名称将是initializeEmptyLinkedList,因为不再有创建部件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.