为什么我的冒泡排序会出现分段错误?

Why am I getting a segmentation fault on my bubble sort?

我的代码中的冒泡排序有效,但是当程序打印新排序的列表时我遇到了分段错误。

我把交换序列打印出来,显示是正确的。排序发生后程序分段错误,它会按顺序打印列表。我不确定这里到底出了什么问题。

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

typedef struct node_t {
  int num;
  struct node_t *next;
  struct node_t *prev;
} node_t;

void add_node (struct node_t **head, int num) {
  struct node_t *new = (struct node_t*)malloc(sizeof(struct node_t));
  struct node_t *last = *head;
  new->num = num;
  new->next = NULL;

  if (*head == NULL) {
    new->prev = NULL;
    *head = new;
    return;
  } else {
    while (last->next != NULL) {
      last = last->next;
    }
    last->next = new;
    new->prev = last;
  }
  return;
}

void swap_num(struct node_t **first, struct node_t **second) {
    struct node_t *temp;
    printf("%d %d\n", (*first)->num, (*second)->num);
    temp->num = (*first)->num;
    (*first)->num = (*second)->num;
    (*second)->num = temp->num;
}

void sort(struct node_t **head) {
  int swapped;
  struct node_t *temp;

  if (*head == NULL){
    printf("list is empty...\n");
    return;
  }
  do {
    swapped = 0;
    temp = *head;

    while (temp->next != NULL) {
      if (temp->num > temp->next->num) {
        swap_num(&temp, &(temp->next));
        swapped = 1;
      }
      temp = temp->next;
    }

  } while (swapped);
}

void print_list (struct node_t **head) {
  struct node_t *temp;

  if (*head != NULL) {
    temp = *head;
    while (temp != NULL) {
      printf("%d ", temp->num);
      temp = temp->next;
    }
    printf("\n");
  }
}

int main (void) {
  struct node_t *head = NULL;
  int new_num, x, y, kill;

  while (new_num != 0) {
    scanf("%d", &new_num);
    if (new_num != 0) {
      add_node(&head, new_num);
      print_list(&head);
    }
  }

  print_list(&head);
  sort(&head);
  printf("------------------\n");
  print_list(&head);
  return 0;

}

这似乎是你的问题:

..\main.c: In function 'swap_num':
..\main.c:40:15: error: 'temp' is used uninitialized in this function [-Werror=uninitialized]
     temp->num = (*first)->num;
     ~~~~~~~~~~^~~~~~~~~~~~~~~

我使用 -Wall-Wextra-Werror 等编译选项得到了它。如果我解决了这个问题,您的代码就不会崩溃。为了修复它,我只是使用了一个 int 临时值而不是 struct node_t* 来保存值。这是我修改后的 swap_num() 函数:

void swap_num(struct node_t **first, struct node_t **second)
{
    int temp;
    printf("%d %d\n", (*first)->num, (*second)->num);
    temp = (*first)->num;
    (*first)->num = (*second)->num;
    (*second)->num = temp;
}