Reputation: 11
This code is a part of a much larger program. There is a main
function within the code and it runs fine, sorry if its messy. Within the function Quick_mode_time
in the second while
loop I get a segmentation error, and I dont understand how I'm messing the array up to cause this. If someone could point me in the right direction I would be very happy!
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>
#define timing_start() start = clock();
#define timing_end(f) msec = (double)(clock()-start) * 1000000.0 /CLOCKS_PER_SEC; \
printf("Calling "#f " takes %10.2f microseconds!\n", msec);
void Quick_mode_time()
{
srand(time(NULL));
int end=500,final=5000;
int a[end],beginning=0;
double t1,t2,t_tot;
printf("***************COMPARISON***************\n");
printf(" quicksort bubblesort (in microseconds)\n");
while(end!=final){
while(beginning<end)
{
a[beginning]=rand()%end; // <--- This causes a segmentation fault
beginning++;
}
printf("N=%d",end);
t1=clock();
quicksort_time(a,0,end);
t2=clock();
t_tot= (double)(t2-t1)*1000/CLOCKS_PER_SEC;
printf("\t%7.3f\t", t_tot);
end+=500;
}
}
void quicksort_time(int x[],int first,int last){
int pivot,j,temp,i;
// The Quick Sorting algorithim is below!
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(x[i]<=x[pivot]&&i<last)
i++;
while(x[j]>x[pivot])
j--;
if(i<j){
temp=x[i];
x[i]=x[j];
x[j]=temp;
}
}
temp=x[pivot];
x[pivot]=x[j];
x[j]=temp;
quicksort_time(x,first,j-1);
quicksort_time(x,j+1,last);
}
}
Upvotes: 0
Views: 75
Reputation: 8514
This line:
int a[end]
creates an array of 500 ints (end is set to 500 in the line before)
This line
a[beginning]=rand()%(end+1-end)+end;
writes to a[beginning]
which is OK as long as beginning
is less than 500.
This seems to be checked by this line just above:
while(beginning<end)
but later on in your code, you have:
end+=500;
so suddenly, end can be > 500, which means beginning can be > 500. Which means you write outside your array boundaries.
One fix would be to change your declaration so that a
is big enough:
int a[final]
Upvotes: 2
Reputation: 26
Your outer while
loop never exits because you never modify the values of end
or final
.
Upvotes: 0