Reputation: 61
I am writing a program for a coursework , basically its idea is to track an element in an array before sorting it and find its index after sorting.It work for numbers up to around 9999 I think but when I enter a large input as 18383833 (on the first input) the mac OS terminal gives me this error: segmentation fault : 11
here is my code :
#include <stdio.h>
#include<stdlib.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
int main()
{
int y; // 2nd INPUT : the nth order of the arriving person
printf("Enter the nth order of the arriving person \n");
scanf("%i" , & y);
int array[y]; // array to store the values of the number of people in queue
int i; //loop counter
printf("Enter the value of ticket of the first person \n");
scanf("%i " , & array[0]);
printf("\n");
for(i=1 ; i<y ; i++) {
array[i]= (31334 * array[i-1]) % 31337;
//printf(" %i \n" , array[i]);
}
int r; //loop counter
bubbleSort(array , y);
for(r=0 ; r<y ; r++) {
printf("%d (%i) \n" , array[r] , r);
}
}
Upvotes: 1
Views: 114
Reputation: 50778
The problem is on this line:
int array[y];
The memory is allocated on the stack, and as stack space is rather limited it blows up.
Replace it by:
int *array = malloc(y * sizeof(*array));
if (array == NULL)
{
printf("Not enough memory\n");
exit(1);
}
and it should work.
Upvotes: 4