简体   繁体   中英

Segfault with Merge Sort on Linked List

My goal with this code is, with a huge linked list, sort by its "count" data, and, in the case of a tie, by its "name" data.

Here is the mergesort algorithm I am implementing:

void split(struct nlist* source, struct nlist** front, struct nlist** back) {
   struct nlist* fast;
   struct nlist* slow;

   if (source == NULL || source->next == NULL) {
      *front = source;
      *back = NULL;
      return;      
   }

   slow = source;
   fast = source->next;

   while (fast != NULL) {
      fast = fast->next;
      if (fast != NULL) {
         slow = slow->next;
         fast = fast->next;
      }
   }

   *front = source;
   *back = slow->next;
   slow->next = NULL;
}

struct nlist* SortedMerge(struct nlist* a, struct nlist* b) {
   struct nlist* result = NULL;

   if (a == NULL)
      return(b);
   else if (b == NULL)
      return(a);

   if (a->count > b->count) {
      result = a;
      result->next = SortedMerge(a->next, b);
   }

   else if (a->count == b->count) {
      if (strcmp(a->name, b->name) > 0) {
         result = a;
         result->next = SortedMerge(a->next, b);
      }
      else {
         result = b;
         result->next = SortedMerge(a, b->next);
      }
   }

   else {
      result = b;
      result->next = SortedMerge(a, b->next);
   }

   return(result);
}

void mergesort(struct nlist **start) {
   struct nlist* head = *start;
   struct nlist* a;
   struct nlist* b;

   if ((head == NULL) || (head->next == NULL)) {
      return;
   }

   split(head, &a, &b);

   mergesort(&a);
   mergesort(&b);

   *start = SortedMerge(a, b);
}

Where I am calling mergesort on the head of my list.

An nlist struct contains three things, an int count, a char* name, and a struct nlist* next.

This code usually does not have a problem, but when testing for edge cases by running this code through all of the dictionary, I get a segfault while sorting the list. It is not an issue with the size of the list, because when I leave out sorting and just return the list unsorted, there are no issues.

When running it through gdb, I see that I get the segfault within SortedMerge, specifically when checking a->count or b->count. The error I get reads

( a=error reading variable: Cannot access memory at address 0x7fffff7fefe8, b=error reading variable: Cannot access memory at address 0x7fffff7fefe0)

Any ideas on what may be causing this?

What's happening is that your code is recursing too deeply and your stack is running into your heap. The way to avoid that is to either limit the number of nodes in the list or rewrite your code non-recursively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM