Search code examples
cbubble-sort

Bubblesort decreasing size each time


This code:

#include <stdio.h>
#define SIZE 10

int main(){

    int a[SIZE]={2,6,4,8,10,12,89,68,45,37};
    int pass;
    int i;
    int hold;
    int dim=10;

    printf("Data items in original order\n");

    for(i=0; i<SIZE; i++){
        printf("%4d", a[i]);
    }

    for(pass=1; pass<SIZE; pass++){
        for(i=0; i<dim; i++){
            if(a[i]>a[i+1]){
                hold=a[i];
                a[i]=a[i+1];;
                a[i+1]=hold;
            }
        }
        dim--;
    }

    printf("\nData items in ascending order\n");

    for(i=0; i<SIZE; i++){
        printf("%4d", a[i]);
    }

    printf("\n");

    return 0;
}

gives me this error:

Data items in original order
   2   6   4   8  10  12  89  68  45  37
Data items in ascending order
   2   4   6   8  10-98850560  12  37  45  68
*** stack smashing detected ***: ./prog terminated

Why? I don't understand. Please explain it to me. Thank you very much. I just don't get it. I don't understand. Please help me. I don't know what to do. Please.


Solution

  • The problem is with this line:

     if(a[i]>a[i+1])
    

    i can go upto dim-1 and dim is 10. So when i becomes 9, the above expression becomes

    if(a[9]>a[10])
    

    You will be accessing the 11th element of an array which contains only 10 elements and thus you will access an out-of-bounds memory address. This is undefined behaviour.

    From wiki:

    The behavior of some programming languages—most famously C and C++—is undefined in some cases. In the standards for these languages the semantics of certain operations is described as undefined. These cases typically represent unambiguous bugs in the code, for example indexing an array outside of its bounds.