【问题标题】:Reverse Linked list (seg fault)反向链表(段错误)
【发布时间】:2014-04-21 13:33:58
【问题描述】:

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

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;
}

【问题讨论】:

  • 你为什么要mallocing任何东西?
  • 由于element *root,您的代码甚至无法编译,因为元素是在之后声明的。
  • 我建议尝试使用 gdb 调试它。您将知道确切的位置以及导致分段错误的原因

标签: c function struct linked-list segmentation-fault


【解决方案1】:

首先我建议您了解什么是封装。我知道这是一个示例,但将代码拆分为 create_list reverse_list destroy_list 是一种很好的做法。

问题出在这里:

   aux1 = lst->root;
   aux2 = NULL;

您丢失了指向 aux1 和 aux2 的指针。这是内存泄漏,使用 gdb 之类的调试器很容易跟踪。当尝试读取 aux1 时,它会得到一个未定义的指针,其中包含垃圾值

您还需要了解 RAII。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 2021-07-16
    • 2011-05-03
    • 2018-02-18
    相关资源
    最近更新 更多