"Abort trap" error in c++

Feb 10, 2017 at 5:33pm
I have an array of size 8, and I send only the second half of the array to my insertion sort. It successfully sorts only the second half of the array, but there is a statement at the bottom, "Abort trap: 6". Below are my main.cc and my insertionSort.cc files. What is causing the "Abort trap: 6" error?


Here is the output:
Before sorting
9 8 10 2 4 6 50 1
After sorting
9 8 10 2 1 4 6 50
Abort trap: 6


main.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <cstdio>
#include "insertionSort.h"

int main() {

    // create array
    int array[] = {9, 8, 10, 2, 4, 6, 50, 1};

    // get size of the array
    int size = sizeof(array) / sizeof(array[0]);

    // display array before reversing
    printf("Before sorting\n");
    for (int i = 0; i < size; i++) {
        printf("%d ", array[i]);
    }

    // new line
    printf("\n");

    // sort only the second half of the array
    insertionSort(array+(size/2), size);

    // display the array again after reversing
    printf("After sorting\n");
    for (int i = 0;i < size; i++) {
        printf("%d ", array[i]);

    } // end of for loop

    // new line
    printf("\n");
  
} // end of main 



insertionSort.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "insertionSort.h"

void insertionSort(int* array, int size) {

    for (int i = 1; i < size; i++) {
        int key = array[i];
        int j = i - 1;

        while (j >= 0 && array[j] > key) {
            array[j+1] = array[j];
            j--;
        } // end of while loop

        // swap
        array[j+1] = key;

        } // end of for loop

} // end of insertionSort 
Feb 10, 2017 at 5:40pm
You're passing size to insertionSort(), when the subarray you're passing actually only has size - size / 2 elements.

Note: size - size / 2 may be a different number from size / 2.
Last edited on Feb 10, 2017 at 5:41pm
Feb 10, 2017 at 5:42pm
you almost certainly ran off your array somewhere. Do you have any additional error message info, a line number or anything at all? If not, can you run in your debugger until it hits that and see where it was and what it was doing?

Topic archived. No new replies allowed.