0
#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.

2
  • 1
    j is not initialized. This may not be the cause of your problem, but it's still bad practice. Commented Feb 14, 2013 at 21:23
  • it doesn't work still, what i mean is that when i try to print out the result, the error occurs. Commented Feb 14, 2013 at 21:28

2 Answers 2

4

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

I have explained this. First paragraph, in the brackets.
1

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.

1 Comment

I too don't understand why j is said not to be initialized, the j = i - 1; clearly does so, as you said.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.