c - 列表头 : get garbage if start parsing from second element

标签 c linux list linked-list garbage

我在我的 C 项目中使用 list_head 结构来定义一个 linked_list。在某些情况下,我需要从第二个元素解析列表,但在这种情况下,我得到了一个带有垃圾值的附加元素。我尝试在我的电脑中使用一个小程序来模拟相同的场景。我遇到了同样的问题:

#include<stdio.h>
#include<stdlib.h>
#include "list.h"

struct struct_report{
        struct list_head list;
        char *report;
};


//Add an element to the linked list
void add_report_to_list(struct list_head *reports, char *report) {
        struct struct_report *report_strct;
        report_strct = calloc(1, sizeof(struct struct_report));
        list_add_tail(&report_strct->list, reports);
        report_strct->report= strdup(report);
}

int main() {
        struct struct_report *retreport;
        LIST_HEAD(reports); //instantiate a struct list_head instance
        add_report_to_list(&reports, "elt1");
        add_report_to_list(&reports, "elt2");
        add_report_to_list(&reports, "elt3");
        add_report_to_list(&reports, "elt4");
        list_for_each_entry(retreport, &reports, list){
                printf("============> no next retreport: %s\n", retreport->report);
        }
        printf("\n");
        list_for_each_entry(retreport, reports.next, list){
                printf("============> Next retreport: %s\n", retreport->report);
        }
        return 1;
} 

list.h 与linux相同:https://github.com/torvalds/linux/blob/master/include/linux/list.h

我得到以下跟踪结果作为执行结果:

============> no next retreport: elt1
============> no next retreport: elt2
============> no next retreport: elt3
============> no next retreport: elt4

============> Next retreport: elt2
============> Next retreport: elt3
============> Next retreport: elt4
============> Next retreport: 

很明显,在我从第一个元素开始正常解析的情况下,我没有任何问题。但在我从列表中的第二个元素开始的情况下,我得到了一个具有奇怪值的额外元素,如垃圾。

有一些解释为什么我得到一个额外的元素吗?以及如何修复它以在 elt4 之前进行解析?

最佳答案

如果您从列表的第一个元素开始(而不是从头开始),那么 list_for_each_entry() 将停止在同一个列表对象中,因为它是一个循环列表。

因此 list_for_each_entry() 将通过头部。并且头部没有附加到条目上。因此,当您尝试引用头列表中的条目时,您将得到垃圾

解决方法:从链表头部开始循环,跳过第一个元素

关于c - 列表头 : get garbage if start parsing from second element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58026125/

相关文章:

C-制作梯形矩阵?

linux - 无法在@INC 中找到 CPAN.pm(@INC 包含 :/usr/local/lib/perl5/usr/local/share/perl5

linux - libc 函数位置在 fork 进程之间发生变化?

r - S4 类列表到数据框

python - 使用唯一集初始化 python 列表

c++ - 在 List c++ 中查找元素

python - 表达式中的变量赋值

c - VIsual Studio 2013 中 C 语言的 GUI

c - 如何使用 malloc 在 C 中创建动态字符串数组

Python 脚本异常挂起,直到 ctrl-c