简体   繁体   中英

GCC Segmentation fault when execute quicksort code

I meet an "segmentation falut" while execute my own quick sort source code in C

in gcc version 4.4.3 with ubuntu 13

the code is look like the below

#include<stdio.h>

void Quicksort(int arr[], int start, int end);
void swap(int *a, int *b);

void main(void){
int arr[] = {15,22,13,27,12,10,20,25};
int iLength=sizeof(arr);

Quicksort(arr, 0, iLength-1);

for(int i=0;i<iLength;++i)
printf("%d", arr[i]);
}


void Quicksort(int arr[], int start, int end)
{
int left = start;
int right = end;

if((end-start)>=1)
{
int pivot = arr[start];
while(right>left)
{
while((arr[left]<=pivot)&&(left<=end)&&(right>left))//Limit check array size
left++;

while((arr[right]>pivot)&&(right>=start)&&(right>=left))
right--;

if(right>left)
swap(&arr[left], &arr[right]);
}//end while

swap(&arr[left], &arr[right]);
Quicksort(arr, start, right-1);
Quicksort(arr, right+1, end);
}//end if
else
{
return;
}
}//end Quicksort

void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

I don't know what is the problem..

many web search results show that it is a memory issue..

but I don't know what is the exact problem in the above code please help...

In main

int arr[] = {15,22,13,27,12,10,20,25};
int iLength=sizeof(arr); 

This iLength will not contain length of array but its size , that is 8*4 (assuming 4 bytes as size of int )= 32 .

If you send this in function and use later in loop -

for(int i=0;i<iLength;++i)
printf("%d", arr[i]);

This will access index out of bound (luckily you got segmentation fault).

To calculate length of array you can do this -

int iLength = sizeof arr/sizeof(int);

And then use it .

Note - void main(void) -> int main(void) or int main(int argc,char **argv) .

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