0

I am having trouble with segmentation error with sorting code. I have tried to understand how I am accessing something that is out of boundaries, but so far no ideas. It runs smoothly in cases where the needle is in the haystack, but fails when it isn't. What is weird about it is that the following code prints all the values (values[996:999]) at the end of the sort code, but fails to print the "Done that" phrase. Checked the sorted values and they are correct. Having no idea why I am accessing memory after that. I am using pointers for swap.

Any help would be appreciated. Snippet of the code:

    printf("%d\n", values[995]);
    printf("%d\n", values[996]);
    printf("%d\n", values[997]);
    printf("%d\n", values[998]);
    printf("%d\n", values[999]);
    printf("Done that");
    return;
}

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

Added requested code:

void sort(int values[], int n)

{
// TODO: implement an O(n^2) sorting algorithm

for(int i = 0; i < n-1; i++){
    int min = i;
    for(int j = i+1; j < n; j++){
        if(values[min] > values[j]){
            min = j;
        }
    }
    if(values[i]  > values[min]){
        swap(&values[i],&values[min]);
    }
}
printf("%d\n", values[995]);
printf("%d\n", values[996]);
printf("%d\n", values[997]);
printf("%d\n", values[998]);
printf("%d\n", values[999]);
printf("Done that");
return;
}
3
  • The clues to the problem lie in what you didn't post. Can you add the code that calls swap(), the declarations for values, the variables that are being swapped, anything related to declaring the number of elements in values, and any directly related code?
    – Cliff B
    Commented Apr 2, 2016 at 5:11
  • Updated the code. I am thinking the conditionals are failing since (>;<), but still confused why it works when the needle is in the haystack. Commented Apr 3, 2016 at 4:05
  • I've tested your sort and swap functions and they seem to be fine. I don't know what's causing your seg faults, unless you're going out of range with your array index. Instead of hardcoding numbers in your printf statements, have you tried using a for loop and limiting the var to n?
    – Cliff B
    Commented Apr 4, 2016 at 3:27

1 Answer 1

0

The problem was in the loop that did the binary search, it had no exit. Solved it by a while loop that runs the program until min <= max.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .