我昨天开始使用C编程并试图实现一个链表(实际上非常基本)。
到目前为止,除了释放列表外,一切都很好。
首先,这是我的代码:
#include <stdio.h>
#include <stdlib.h>
/*
* Struct for elements of the linked list
*/
struct element {
struct element* nextelement;
int value;
};
/*
* Struct for a list itself
*/
struct liste {
struct element* headelement;
};
/*
* Function to create new elements
*/
struct element* createelement(int value) {
struct element* dummyelement = malloc(sizeof(struct element));
dummyelement->nextelement = NULL;
dummyelement->value = value;
return dummyelement;
}
/*
* Function to create new (empty) lists
*/
struct liste* createlist() {
struct liste* dummylist = malloc(sizeof(struct liste));
dummylist->headelement = NULL;
return dummylist;
}
/*
* Add an element to a given list
*/
void addelement(struct liste* liste, int value) {
struct element* dummyelement = createelement(value);
if (liste->headelement == NULL) {
liste->headelement = dummyelement;
} else {
struct element* iterelement = liste->headelement;
while (iterelement->nextelement != NULL) {
iterelement = iterelement->nextelement;
}
iterelement->nextelement = dummyelement;
}
}
/*
* Plot the elements of a given list
*/
void plotlist(struct liste* liste) {
if (liste->headelement != NULL) {
struct element* iterelement = liste->headelement;
printf("%d\n", iterelement->value);
while (iterelement->nextelement != NULL) {
iterelement = iterelement->nextelement;
printf("%d\n", iterelement->value);
}
} else {
printf("Where is my head?\n");
}
}
/*
* This should completely remove the list, but it fails...
*/
void removelist(struct liste* liste) {
if (liste->headelement != NULL) {
struct element* iterelement = liste->headelement;
struct element* nextelement = iterelement->nextelement;
free(iterelement);
while (nextelement != NULL) {
iterelement = nextelement;
nextelement = iterelement->nextelement;
free(iterelement);
}
}
free(liste);
}
int main(void) {
/*
* Creates a new list
* Plots the (empty) list
* Adds two elements to the list
* Plots the list again
* Removes the list
* Last plot shouldn't really happen, but it does.
*/
struct liste* mylist = createlist();
printf("First plot.\n");
plotlist(mylist);
addelement(mylist, 1);
addelement(mylist, 2);
printf("Second plot.\n");
plotlist(mylist);
removelist(mylist);
printf("Third plot.\n");
plotlist(mylist);
return 0;
}
我得到以下输出:
First plot.
Where is my head?
Second plot.
1
2
Third plot.
33
很明显,&#33; 33&#39;是我的问题。我真的不知道这可能是什么输出...此外,我不知道为什么我的重新组合&#39;没有正常工作。我释放了我用“malloc”分配的所有东西。我做错了什么?
答案 0 :(得分:1)
您不在plotlist
内查看您的列表是否确实存在。您直接尝试访问headelement
。更好地做到以下几点:
void plotlist(struct liste* liste) {
if(liste == NULL){
printf("This list does not even exist.\n");
}
else if (liste->headelement != NULL) {
// ...
} else {
printf("Where is my head?\n");
}
}
由于removelist
也会释放列表结构,因此最好将指针设置为main中的NULL
。否则,在访问释放的内存时会出现未定义的行为。
int main(void) {
// ...
removelist(mylist);
mylist = NULL;
printf("Third plot.\n");
plotlist(mylist);
return 0;
}