Vscode shows nothing, online compiler shows segmentation fault, trying to sort an array

53 Views Asked by At

I was trying to sort an array on my own without copying any pre-tought method in my terminal the code gets compiled but I guess it keeps on running in the online compiler it shows segmentation fault.

#include <stdio.h>
int main(){
    int arr[]={2,45,23,12,34,6,23,78,9,33};  //minimum of an array
    int len=sizeof(arr)/sizeof(int);
    //printf("%d\n",len);
    int min;
    min=arr[0];
    int temp;
    for(int j=0;j<len;j++){
        for(int i=0;i<len;i++){
            if(arr[i]<min){
                min=arr[i];
                temp=i;
            }
        }
        int v;
        v=arr[j];
        arr[j]=min;
        arr[temp]=v;
    }
    printf("%d\n",min);
    for(int k=0;k<len;k++){
        printf("sorted array is %d\n",arr[k]);
    }
    
    return 0;
}
1

There are 1 best solutions below

3
tmt On

As Johhny Mopp mentioned in the comment, the temp=i assignment may not execute. In fact, in your code, it never reaches because you have set min=arr[0] which is always the minimum =2 and if(arr[i]<min) never passes. In your case, temp remains uninitialized. Try putting minimum value at another index in array and your code should assign temp=i.

Now the question is - What happens with uninitialized variable temp?

temp is a local variable and compilers are free to set a value of their choice. Read here for more information on this topic.

It's possible that online compiler is setting temp to a value that makes arr[temp]=v an illegal read from out of bound index temp resulting into segfault.

If you tried another compiler, it might not segfault e.g. Apple clang on my macOS sets temp=0 at assignment and your code never fails.

By the way, your code needs correction for sorting the array. There are better ways, so I will leave up to you to figure out the changes :).

Here is the updated code with minimal changes:

#include <stdio.h>

int main() {
    int arr[] = {2, 45, 23, 12, 34, 6, 23, 78, 9, 33};  //minimum of an array
    int len = sizeof(arr) / sizeof(int);
    //printf("%d\n",len);
    int min;
    int temp = 0; // Make sure it is initialized and not left up to compilers to decide
    for (int j = 0; j < len; j++) {
        min = arr[j];
        for (int i = j; i < len; i++) {
            if (arr[i] <= min) {
                min = arr[i];
                temp = i;
            }
        }
        int v;
        v = arr[j];
        arr[j] = min;
        arr[temp] = v;
    }
    printf("%d\n", min);
    for (int k = 0; k < len; k++) {
        printf("sorted array is %d\n", arr[k]);
    }
    
    return 0;
}