简体   繁体   中英

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:

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

I post the code of the insert, main, and the quicksort function.

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. You can't mix up data structures like that.

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