Search code examples
arrayscsortingfor-loopbubble-sort

Stack around Variable a is corrupted


#include<stdio.h>

int main(void)
{
    int array[10] = { 10,2,9,4,5,6,7,8,3,1 };
    /*Implementing Bubble Sort */
    int temp;
    for (int i = 0; i < 9; i++)
    {
        for (int j = 0; j < 10 - i; j++)
        {
            if (array[j] > array[j + 1])
            {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }
    for (int i = 0; i < 10; i++)
    {
        printf("%d ", array[i]);
    }
}

When I try to run the program I'm getting values sorted but one value has some garbage value and the dialogue box appears that stack around variable is corrupted in VS 2019. In some other compiler I'm getting 0 in place of 10 in compiler.


Solution

  • The inner for .loop

    for (int j = 0; j < 10 - i; j++)
    {
        if (array[j] > array[j + 1])
        {
            temp = array[j];
            array[j] = array[j + 1];
            array[j + 1] = temp;
        }
    }
    

    invokes undefined behavior because when j is equal to 9 for the first iteration of the outer loop that is when i is equal to 0 the index in the expression array[j + 1] can be equal to 10 that results in accessing the memory beyond the array.

    Rewrite the loop like

    for (int j = 1; j < 10 - i; j++)
    {
        if (array[j-1] > array[j])
        {
            temp = array[j-1];
            array[j-1] = array[j];
            array[j] = temp;
        }
    }