sameer manek
sameer manek

Reputation: 763

Segmentation fault in my program

My sorting program results in a "segmentation fault 11":

#include <stdio.h>

int main() 
{
    // Asking user for number of inputs in an array
    int n;
    do {
        printf ("enter the number of intigers you want to sort\n");
        scanf("%d",&n);
    }while (n<=1);

    int sort [n];
    printf ("please enter %d numbers\n",n);
    for (int i=0; i<n; i++) {
        scanf("%d",&sort[i]);
    }
    printf("you entered\n ");

    for (int i=0; i<n; i++) {
        printf(" %d ",sort[i]);
    }
    printf("\n");

    int k,c,i,x;
    for (i=0;i<n;i++) {
       if (sort[i]<sort[i-1]){
           k=i-2;
           while (sort[k]>sort[i]){
               k--;
           }
           k++;
           x =sort[i];
           c=i;
           for (c=i;c>k;c++){
              sort[c-1]=sort[c];
           }
           sort[k]=x;    
        }
    }
    printf ("Sorted numbers :-\n");
    for (int i=0; i<n; i++) {
        printf ("%d ",sort[i]);
    }
     printf ("\n");
    return 0;
}

Now I have looked up the internet and found that it is caused because a variable has value that exceeds the system's memory limit. But cannot understand that concept.

Upvotes: -1

Views: 61

Answers (3)

Ar4i
Ar4i

Reputation: 31

In addition to all said before:

       c=i;
       for (c=i;c>k;c++){
          sort[c-1]=sort[c];
       }
       sort[k]=x;  
  1. i can be 0 -> c can be 0 -> sort[c-1] would also result in accessing array out of bounds.
  2. There is no need to initialize c=i twice. It is enough to do it in the loop-declaration

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234635

  1. k = i - 2; looks unstable for low values of i.

  2. sort[i - 1] is undefined when i is zero.

The thing causes the behaviour of sort[k] to be undefined.

Moral of the story: check all the array indexes before attempting to retrieve an array element. Your debugger will help you here.

Upvotes: 3

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

   for (i=0;i<n;i++)
   {
      if (sort[i]<sort[i-1])

You are accessing array out of its bounds.Maybe you want to start your loop from 1.Also

   k=i-2;
   while (sort[k]>sort[i])

will access index beyond 0 for example if i is 0 or 1 or 2

Upvotes: 3

Related Questions