简体   繁体   中英

Segmentation Fault Before function is even called

When I try executing this code, the code crashes before the cout statement in print_array even executes. I have no clue why ! However, if I comment out the call to mergesort in the main function, the print_array executes fine.

#include<iostream>
using namespace std;
void print_array( int A[], int n)
{
    int i;
    cout<<"\n Array elts:\t";
    for(i=0;i<n;i++) cout<<A[i]<<" ";
}
void mergesort(int A[], int beg, int end)
{
    if(beg>end) return;
    mergesort(A,beg,(beg+end)/2);
    mergesort(A, ((beg+end)/2)+1, end);
    int B[end-beg+1],i,j,k;
    i=beg; j=(beg+end)/2;
    k=0;
    while(i<(beg+end)/2 && j<end)
    {
        if(A[i] < A[j]) B[k++]=A[i++];
        else B[k++]=A[j++];
    }
    while(i<(beg+end)/2) B[k++]=A[i++];
    while(j<end) B[k++]=A[j++];
    for(i=beg; i<end; i++) A[i]=B[i];       

}   
int main()
{
    int n=10;
    int A[]={1,23,34,4,56,60,71,8,99,0};
    print_array(A,n);
    mergesort(A,0,n);
    print_array(A,n);
}

Update: Using endl will flush the output and the print_array values will get displayed on the screen. Apart from this, the reason I got a seg fault was because I had not included the equality check in mergesort . Here is the updated code:

#include<iostream>
using namespace std;
void print_array( int A[], int n)
{
    int i;
    cout<<"\n Array elts:\t";
    for(i=0;i<n;i++) cout<<A[i]<<" ";
}
void mergesort(int A[], int beg, int end)
{
    if(beg>=end) return;
    mergesort(A,beg,(beg+end)/2);
    mergesort(A, ((beg+end)/2)+1, end);
    int B[end-beg+1],i,j,k;
    i=beg; j=(beg+end)/2;
    k=0;
    while(i<(beg+end)/2 && j<end)
    {
        if(A[i] < A[j]) B[k++]=A[i++];
        else B[k++]=A[j++];
    }
    while(i<(beg+end)/2) B[k++]=A[i++];
    while(j<end) B[k++]=A[j++];
    for(i=beg; i<end; i++) A[i]=B[i];       

}   
int main()
{
    int n=10;
    int A[]={1,23,34,4,56,60,71,8,99,0};
    print_array(A,n);
    mergesort(A,0,n);
    print_array(A,n);
}

The code is by no means doing what it should but it isn't giving seg faults anymore. Thanks guys !

Look at the last line in mergesort : You're accessing elements in B from beg to end , but B is zero indexed. That's one problem; there may be more.

My first though is that this is a Stack Corruption which is leading to a "Stack Overflow" when you call other methods. Try getting additional information in GDB, try compiling increasing the debugging level and turning off the optimizations of gcc (ie, -g3 -O0).

Moreover, you can use the "valgrind" software to find the corruption and post the results here. (Sorry for requesting this here, but I cannot make comments).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM