[英]I'm receiving Invalid read of size 8 when running Valgrind in C
I've written a C linkedlist program and am running a simple test harness to ensure that all functions are working optimally.我已经编写了一个 C 链表程序,并且正在运行一个简单的测试工具,以确保所有功能都以最佳方式运行。 However, despite there being no memory leaks, according to Valgrind I'm having two issues with my code, these being
但是,尽管没有内存泄漏,但根据 Valgrind 的说法,我的代码有两个问题,它们是
Header file: LinkedList.h头文件:LinkedList.h
typedef struct LinkedListNode
{
void* data;
struct LinkedListNode* next;
struct LinkedListNode* previous;
} LinkedListNode;
typedef struct
{
LinkedListNode* head;
LinkedListNode* tail;
int size;
} LinkedList;
The removeStart function in linkedlist.c Linkedlist.c 中的 removeStart 函数
void* removeStart(LinkedList* list)
{
LinkedListNode* curr = list->head;
void* ptr;
if (curr->next == NULL)
{
free(curr);
list->head = NULL;
}
if (curr->next != NULL) //This is where the Invalid read of size 8 error occured
{
ptr = curr -> data;
list -> head = curr -> next;
free(curr);
curr = NULL;
list -> head -> previous = NULL;
list->size--;
}
return ptr;
}
The removeLast function removeLast 函数
void* removeLast(LinkedList* list)
{
LinkedListNode* curr = list -> head;
LinkedListNode* secondLast;
void* ptr;
if (isEmpty(list) == 0)
{
printf("List is empty");
}
else
{
while (curr->next != NULL)
{
secondLast = curr;
curr = curr->next;
}
if (curr == list->head)
{
list -> head = NULL;
}
}
ptr = curr->data;
list->size--;
list -> tail = secondLast;
secondLast->next = NULL; //This is where Use of uninitialised value of size 8 occured
free(curr);
curr = NULL;
return ptr;
}
In removeStart
if curr->next == NULL
then you free curr but use it again 2 lines down.在
removeStart
如果curr->next == NULL
则您释放 curr,但再次使用它向下 2 行。
In removeLast
if the list is empty then secondLast
is never set.在
removeLast
如果列表为空,则永远不会设置secondLast
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.