Hey I'm currently writing a program which takes a file of data sorts it (using bubble sort) and for some reason I keep getting a segmentation fault.

#include <stdio.h>
#include <stdlib.h>

void compare(int numberstocheck[], int n) 
{
  int i, j, k;
  int thebucket[n];
  for(i = 0; i < n; i++) {
    thebucket[i] = 0;
  }
  
  for(i = 0; i < n; i++) {
    thebucket[numberstocheck[i]]++;
  }
  puts("2");
  for(i = 0, j = 0; i < n; i++) {
    for(k = thebucket[i]; k > 0; k--){
      numberstocheck[j++] = i;
    }
  }
}


int main( int argc, char *argv[] )
{
  if(argc == 3)
  {  
    FILE *numbersfile;
    numbersfile = fopen(argv[1], "r");
    int numberslength = atoi (argv[2]);
    int numberstocheck[numberslength];

    //Get the numbers from file
    char numbersarray[50];
    int count = 0;
    while (fgets(numbersarray, 50, numbersfile) != NULL)
    {
      numberstocheck[count] = atoi(numbersarray);
      count++;
    } 
    //Sort the array   
    compare(numberstocheck, numberslength);
 
    
    double percentile = numberslength;
    percentile = 9 * (percentile / 10);
    int othernumber = percentile - 1;
    int lowernumbers = numberstocheck[othernumber];
    int booleanvalue = 0;
    int finalpercentile = -1;
    for(count = othernumber + 1; count < numberslength && booleanvalue == 0;
	count++)
	if (numberstocheck[count] > lowernumbers)
	{
	finalpercentile = numberstocheck[count];      
	booleanvalue = 1;    
      }
      
    printf("The 90th percentile of this file is: %d\n", finalpercentile);  
    
    fclose(numbersfile); 
   }
   else
     printf("Something went wrong, please check your input!\n");
     exit(EXIT_FAILURE);
}

Edited 5 Years Ago by dbuckle: n/a

for some reason I keep getting a segmentation fault

The reason is nearly always an out of range index. Verify that any indices you use are between 0 and n.

What you need to do is debug your program. Step through it and check the indices. You can do this programmatically by adding debug checks at risky points if desired. For example:

void compare(int numberstocheck[], int n) 
{
  int i, j, k;
  int thebucket[n];
  for(i = 0; i < n; i++) {
    thebucket[i] = 0;
  }
 
  for(i = 0; i < n; i++) {
    int index = numberstocheck[i];

    if (index < 0 || index >= n) {
      printf("out of range at index numberstocheck[%d] with value %d\n", i, index);
      getchar();
    }

    thebucket[numberstocheck[i]]++;
  }

  for(i = 0, j = 0; i < n; i++) {
    for(k = thebucket[i]; k > 0; k--){
      if (j < 0 || j >= n) {
        printf("out of range at index numberstocheck[%d]\n", j);
        getchar();
      }

      numberstocheck[j++] = i;
    }
  }
}

Anywhere you have a potentially unbounded array index, check the index and display a debug message if it fails. Note that things like thebucket[i] are safe in a loop that's strictly controlled.

Comments
Helpful advice for finding index overruns!
This article has been dead for over six months. Start a new discussion instead.