請參閱下面給出的這個程序。它在delete_node函數結束時崩潰。請讓我知道發生了什麼問題。它在delete_node(5)調用結束時崩潰。調用delete_node後的printf語句不會執行。鏈接列表的分段錯誤
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
typedef struct _list{
int data;
struct _list *next;
}list;
list* create_list(int val);
list* add_list(int val, bool ad_end);
int delete_node(int val);
void print_list(void);
list* head = NULL;
list* curr = NULL;
int main()
{
int val = 10;
list* mylist;
mylist = create_list(5);
add_list(val, true);
add_list(20, true);
add_list(30, true);
add_list(25, true);
print_list();
delete_node(5);
printf("\n I am here in main \n");
print_list();
return 0;
}
list* create_list(int val)
{
list* ptr =(list*) malloc(sizeof(list));
head = curr = ptr;
ptr->data = val;
ptr->next = NULL;
return ptr;
}
list* add_list(int val, bool add_end)
{
list* ptr =(list*) malloc(sizeof(list));
ptr->data = val;
ptr->next = NULL;
if(add_end) {
curr->next = ptr;
curr = ptr;
} else {
ptr->next = head;
head = ptr;
}
return ptr;
}
int delete_node(int val)
{
list* tmp = NULL;
list* prev;
tmp = head;
while(tmp){
if(tmp->data == val) {
printf(" Found the node to be deleted\n");
prev->next = tmp->next;
if(tmp == head) {
head = tmp->next;
}
free(tmp);
printf(" Head data is %d \t head %p\t add-nxt %p\n", head->data, head, head->next);
break;
} else {
prev = tmp;
tmp = tmp->next;
}
printf("Node to be deleted not found \n");
}
return 1;
}
void print_list(void)
{
list* tmp = head;
while(tmp != NULL) {
printf("addr %p\t addr next %p\n", tmp, tmp->next);
printf(" Data is %d \n", tmp->data);
tmp = tmp->next;
}
printf("\n");
}
你嘗試在調試器中運行的代碼?這可以幫助您更快速地找到問題,而不僅僅是要求其他人爲您進行調試。 –
嘗試刪除'delete_node'處的第一個元素時,未設置'prev'。 – BLUEPIXY
這不是你的錯誤,但prev-> next = tmp-> next;如果prev未初始化(即數據== val對於第一個值爲真),將成爲段錯誤的源。 – LostBoy