基本上,我正在尝试在C中实现单链表,我正在使用valgrind来检查是否有任何内存泄漏。 Valgrind显示内存泄漏“可能已丢失”,但我释放了堆上的每个malloc,我不确定它在哪里发生。
以下是我的记忆错误图片的链接:http://imgur.com/a/E1Ko0
这是我的代码,输出显示在valgrind图像中。
#include <stdio.h>
#include <stdlib.h>
/* defines node object */
struct node
{
/* node holds data */
long data;
/* next pointer */
struct node *next;
};
struct node * buildList (void);
long getElement (struct node *, int index);
int lenList(struct node *Head);
void insertList(struct node **Head);
void delete_List (struct node **Head);
/* builds a list of four nodes */
struct node * buildList (void)
{
struct node * head = (struct node *) malloc(sizeof(struct node));
struct node * second = (struct node *) malloc(sizeof(struct node));
struct node * third = (struct node *) malloc(sizeof(struct node));
struct node * fourth = (struct node *) malloc(sizeof(struct node));
head ->data = 1;
head ->next = second;
second ->data = 2;
second ->next = third;
third ->data = 3;
third ->next = fourth;
fourth ->data = 4;
fourth ->next = NULL;
/* returns pointer to first node*/
return head;
}
/* gets value at list index */
long getElement(struct node *Head, int index)
{
for (int i = 0; i<index; i++)
{
Head = Head -> next;
}
return Head -> data;
}
/* gets length of list */
int lenList(struct node *Head)
{
int counter = 0;
while (Head != NULL)
{
counter++;
Head = Head->next;
}
return counter;
}
/* inserts node at beginning of list, resets head pointer to new node */
void insertList(struct node **Head)
{
struct node *newnode = (struct node *) malloc (sizeof(struct node));
newnode->data = 0;
newnode->next = *Head;
/* head pointer now points to first node */
*Head = newnode;
}
/* deletes and deallocates list memory */
void delete_List (struct node **Head)
{
struct node *temp;
struct node *current = *Head;
while (current!=NULL)
{
temp = current;
current = current -> next;
free(temp);
}
/* mark list as empty */
*Head = NULL;
}
int main(void)
{
struct node * headpointer = buildList();
printf("Initial length of list is: %d\n", lenList(headpointer));
insertList(&headpointer);
printf("After inserting node, list length is: %d\n", lenList(headpointer));
printf("The data at index 1 is: %ld\n", getElement(headpointer, 1));
delete_List(&headpointer);
printf("Headpointer should now be equal to null: %x\n", headpointer);
return 0;
}