简体   繁体   English

Quicksort C-细分错误

[英]Quicksort C - Segmentation fault

I made a single Linked list. 我列出了一个链接列表。 Now I want to make a quicksort but I'm getting segmentation fault and can't find where the problem is. 现在,我想做一个快速排序,但是我遇到了细分错误,找不到问题所在。

Invalid read of size 8
   at 0x400659: quicksort (liiista.c:23)   
   by 0x4008FE: main (liiista.c:117)
   Address 0x0 is not stack'd, malloc'd or (recently) free'd

Line 23 is the following: 第23行如下:

while( (strcmp(arr[left]->ele,arr[pivot]->ele) <= 0) && left < end)

I post the code of the insert, main, and the quicksort function. 我发布了insert,main和quicksort函数的代码。

typedef struct celda{
  char* ele;
  struct celda *next;
}*tList;


void quicksort(tLista *arr, int begin, int end){
  char* temp;
  int left, right, pivot;

  if(begin < end){

    pivot = begin;
    left = begin;
    right = end;


    while(left < right){
        while( (strcmp(arr[left]->ele,arr[pivot]->ele) <= 0) && left < end) {
            left++;
        }   
        while( (strcmp( arr[right]->ele, arr[pivot]->ele) > 0)){
            right--;        
        }
        if(left<right){
            temp = arr[left]->ele;
            arr[left]->ele = arr[right]->ele;
            arr[right]->ele = temp;
        }                       
    }

    temp = arr[pivot]->ele;
    arr[pivot]->ele = arr[right]->ele;
    arr[right]->ele = temp;

    quicksort(&(*arr),begin,right-1);
    quicksort(&(*arr),left+1, end);

  } 
}

void insert(tList *myList, char* ele){

  tList node = (tList)malloc(sizeof(struct celda));
  node->ele = ele;
  node->next = *myList;
  *myList = node;

}


int main(){

  tList myList = NULL;
  insert(&myList,"a");
  insert(&myList,"b");
  insert(&myList,"c");
  insert(&myList,"d");
  insert(&myList,"e");

  quicksort(&myList,0,4);

  return 1;
}

I have try to find the mistake but I couldn't. 我已经尝试找到错误,但是我找不到。 Thanks in advance! 提前致谢!

In your quicksort function, it expects to be passed an array of pointers to struct celda , however you're passing in the address of the address of the first node in a linked list. 在您的quicksort函数中,它希望传递一个指向struct celda的指针数组,但是您正在传递链表中第一个节点的地址。 You can't mix up data structures like that. 您不能像这样混淆数据结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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