[英]Reverse Linked list (seg fault)
My goal is to create a function which performs reverse operation on a List and return the reverse 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.
The problem is that I am getting segmentation fault core dumped. 问题是我正在丢弃分段错误核心。
Please help me to solve this. 请帮我解决这个问题。
Thank's in advance 提前致谢
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;
}
First of all i advice You to learn what is encapsulation. 首先,我建议您学习什么是封装。 I understand this is a sample but splitting the code into create_list reverse_list destroy_list is a great practice. 我知道这是一个示例,但是将代码拆分为create_list reverse_list destroy_list是一个很好的实践。
The problem is here: 问题在这里:
aux1 = lst->root;
aux2 = NULL;
You loose pointer to aux1 and aux2. 您松开aux1和aux2的指针。 That's a memory leak and it's real easy to track with a debugger like gdb. 那是内存泄漏,使用像gdb这样的调试器很容易跟踪。 when while tries to read aux1 it gets an undefined pointer with trash value in it 当while尝试读取aux1时,它获得了一个带有垃圾值的未定义指针
You also need to read about RAII. 您还需要阅读有关RAII的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.