C 反向链表(seg故障)

C 反向链表(seg故障),c,function,struct,linked-list,segmentation-fault,C,Function,Struct,Linked List,Segmentation Fault,我的目标是创建一个对列表执行反向操作并返回反向列表的函数 Root --> First element in the List, size --> Size of the list, str --> Data (string) in the list and next --> Points to next node in the List. 问题是,我得到了分割错误核心倾倒 请帮我解决这个问题 谢谢,这是事先准备好的 typedef struct {

我的目标是创建一个对列表执行反向操作并返回反向列表的函数

Root --> First element in the List, 
size --> Size of the list, 
str -->  Data (string) in the list and 
next --> Points to next node in the List. 
问题是,我得到了分割错误核心倾倒

请帮我解决这个问题

谢谢,这是事先准备好的

typedef struct {
    element *root;
    int size;
} list;


typedef struct _element {
    char* str;
    struct _element *next;
} element;



list* reverse_list(list *lst) {
    lst = malloc(sizeof(list));

    element *aux1, *aux2, *aux3;
    aux1 = malloc(sizeof(element));
    aux2 = malloc(sizeof(element));
    aux3 = malloc(sizeof(element));

    aux1 = lst->root;
    aux2 = NULL;

    while (aux1->next != NULL) {
        aux3 = aux1->next;
        aux1->next = aux2;
        aux2 = aux1;
        aux1 = aux3;
    }

    lst->root = aux1;

    return lst;
}

首先,我建议您了解什么是封装。我知道这是一个示例,但将代码拆分为create\u list reverse\u list destroy\u list是一个很好的实践

问题在于:

   aux1 = lst->root;
   aux2 = NULL;
您松开了指向aux1和aux2的指针。这是内存泄漏,使用gdb之类的调试器很容易跟踪。当while试图读取aux1时,它会得到一个包含垃圾值的未定义指针


您还需要阅读有关RAII的内容。

为什么要删除任何内容?您的代码甚至无法编译,因为
element*root
,因为元素是在之后声明的。我建议尝试使用gdb对其进行调试。你会知道确切的位置,以及是什么导致了分割错误