Search code examples
cbubble-sort

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


The bubble sort in my code works, but when the program goes to print the newly sorted list I get a segmentation fault.

I print out the swap sequence and it shows that it is correct. The program segmentation faults after the sorting happens and it goes to print the list in order. I'm not sure exactly whats going wrong here.

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

}

Solution

  • This seems to be your problem right here:

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

    I got this using compile options such as -Wall, -Wextra, and -Werror. If I fix that, your code does not crash. To fix it I just used an int temporary to hold the value instead of a struct node_t*. Here's my revised swap_num() function:

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