speedyjiji
speedyjiji

Reputation: 11

Segmentation fault when implementing insertion sort

#include <iostream>

using namespace std;

int main(){
    int a[6] = {5, 2, 4, 6, 1, 3}; // create an array of size 6
    int j, key = 0;
    for (int i = 1; i < 6; i++) {
        key = a[i];
        j = i - 1;
        while ((j >= 0) && (a[j] > key)) {
            a[j + 1] = a[j];
            j -= 1;
        }
        a[j + 1] = key;
    }
    for (int l = 0; l < 6; l++) { 
        cout << a[l];
    }
    return 0;
}

I'm trying to test my insertion sort code using an array the code complies but when I try to execute the a.out file, it gives me "Segmentation Fault", I look up what segmentation fault is, it's basically an error that we are trying to access the forbidden memory location, however, I'm wondering where exactly is the error in my code. Also, if i get rid of the

for (int l = 0; l < 6; l++) { 
    cout << a[l];
}

no error is found.

Upvotes: 0

Views: 527

Answers (2)

Thomas
Thomas

Reputation: 5138

sorting is one of the algorithms in the stl. you should really be using std::sort like

std::sort( a, a+6 );

PS: j is initialized before use in the line

j = i - 1;

so that is not the cause of the crash.

Upvotes: 1

us2012
us2012

Reputation: 16253

Your variable j is not initialized and so may be anything when you first access a[j]. That causes the segmentation fault. (int j,key =0; only sets key to 0 but not j.)

Always compile your code with -Wall, this would have told you about the use of the uninitialized variable. (Correction: My gcc 4.7 doesn't catch it. How lame.)

(The reason why the error goes away when you remove the printing is that you have compiler optimizations turned on: The compiler then notices that you never do anything practical with the computed values and arrays and just throws everything into the bin and gives you an empty program.)

Upvotes: 4

Related Questions