Search code examples
cxcodebubble-sort

Bad Access in C Bubblesort for same functions using Xcode


I'm learning C using Xcode so I've been practicing the bubble sort algorithm. You can see my code (failing) here as bubbleSort1 function and bubbleSort2 passing.

#include <stdio.h>

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

void bubbleSort1(int arr[], int n)
{
    int i, j;
    for (i = 0; i < n-1; i++)


        for (j = 0; i < n-i-1; j++)
            if(arr[j] > arr[j+1])
                swap(&arr[j], &arr[j+1]);
}

void bubbleSort2(int arr[], int n)
{
    int i, j;
    for (i = 0; i < n-1; i++)

        // Last i elements are already in place
        for (j = 0; j < n-i-1; j++)
            if (arr[j] > arr[j+1])
                swap(&arr[j], &arr[j+1]);
}

void printArray(int arr[], int size){
    printf("Array:\t");
    for(int i=0; i<size;i++){
        printf("%d ", arr[i]);
    }
    puts("\n");
}

int main(){

    int array2[8] = {9, 15, 7, 4, 1, 11, 3, 4};
    int length2 = sizeof(array2)/sizeof(array2[0]);
    printArray(array2,length2);
    bubbleSort2(array2,length2);
    printArray(array2, length2);

    int array1[8] = {9, 15, 7, 4, 1, 11, 3, 4};
    int length1 = sizeof(array1)/sizeof(array1[0]);
    printArray(array1,length1);
    bubbleSort1(array1,length1);
    printArray(array1, length1);

    return 0;
}

From the code you can see that bubbleSort1 and bubbleSort2 are almost the same, except by the commented line.

However I have some strange "Bad Access" error when running my code, and the XCode debugger kept telling me that j in bubblesort1 is 667, and an error in line 24. You can see an snapshot here:

As you can see bubbleSort1 and bubbleSort2 are similar

In the image you can see that bubbleSort2 runs without problems, despite being the same as bubbleSort1.

The same error happens when run each function by itself.

Is this an Xcode error? Or am I missing something, considering I'm just beginning to learn C?


Solution

  • bubbleSort1 has an incorrect for loop.

    for (j = 0; i < n-i-1; j++) should be for (j = 0; j < n-i-1; j++)