c - 在 C 中运行 Valgrind 时,我收到大小为 8 的无效读取
问题描述
我编写了一个 C 链表程序,并且正在运行一个简单的测试工具,以确保所有功能都以最佳方式工作。然而,尽管没有内存泄漏,但根据 Valgrind 的说法,我的代码有两个问题,这些是
- 大小为 8 的无效读取
- 使用大小为 8 的未初始化值任何人都可以帮助解决这个问题,因为我不确定是什么导致了这个问题。
头文件:LinkedList.h
typedef struct LinkedListNode
{
void* data;
struct LinkedListNode* next;
struct LinkedListNode* previous;
} LinkedListNode;
typedef struct
{
LinkedListNode* head;
LinkedListNode* tail;
int size;
} LinkedList;
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;
}
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;
}
解决方案
在removeStart
if curr->next == NULL
then you free curr 但在 2 行之后再次使用它。
如果removeLast
列表为空,则secondLast
永远不会设置。
推荐阅读
- python - 跨多个熊猫列循环 lambda 函数
- azure - Azure Devops Piepeline - Yaml Powershell 脚本路径
- javascript - 如何在 VueJS 组件中使用全局变量
- r - 在R中的文件名中保存带有变量文本的文件
- pdf - GHOSTSCRIPT - PS 到 PDF 转换纸张大小
- c# - 如何在实体框架中传递计数内的整数列表
- sql - MySQL LEFT JOIN 与 GROUP BY 和 WHERE 子句查询
- javascript - reactjs 道具在路线创建中丢失
- php - 将几个单独的 SQL 查询重写为一个
- javascript - 使用反应导航的启动画面