-3

when i am trying to run this code for input 1 and 1000 it shows me segmentation fault .what will be the correction in this code ?

void sorting(int sum[],long int k);

int main() {
    int sum[100000]; 
    int L,R,i,j;
    long int k=0;

    cin>>L;

    cin>>R;
    for(i=L;i<=R;i++)
    {
        for(j=i;j<=R;j++)
        {
            sum[k]=i^j;
            k++;
        }
    }

    sorting(sum,k);

    cout<<sum[k-1];
    return 0;
}

void sorting(int sum[],long int k)
{
    int i,j;
    long int temp;
    for(i=0;i<k;i++)
    {
        for(j=0;j<k;j++)
        {
            if(sum[i]<=sum[j])
            {
                temp=sum[i];
                sum[i]=sum[j];
                sum[j]=temp;
            }
        }
    }

}
dragosht
  • 3,237
  • 2
  • 23
  • 32
  • 1
    Use a debugger to narrow the problem down – Ed Heal Feb 07 '15 at 10:20
  • possible duplicate of [What can cause segmentation faults in C++?](http://stackoverflow.com/questions/6923574/what-can-cause-segmentation-faults-in-c) – mip Feb 07 '15 at 12:01

2 Answers2

4

The segmentation fault is caused by stack overflow. This line:

int sum[100000]; 

sum uses 400K spaces of stack, which is bigger than the normal size of stack.

To fix the problem, you can use std::vector to implement sum instead.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
2

I think the problem is not in the stack size, but content of variable k

for(i=L;i<=R;i++)
{
    for(j=i;j<=R;j++)
    {
        sum[k]=i^j;
        k++;
    }
}

For L = 1, R = 1000, this loop makes k as large as 500500, which exceeds the size of sum array, which has 100000 elements.

To dirty-fix this error you could make sum array larger, but, since stack size indeed can be limited, it's better to allocate huge arrays on a heap. This is also more elegant solution in your case, because you can dynamically set required size of the array.

To allocate memory on heap you can use std::vector or C++11 unique_ptr<int[]> (you could also use new[] and delete[], although recently it is advised to use methods mentioned previously, because they secure some aspects of dynamic memory allocation).

To create array with unique_ptr<int[]>

std::unique_ptr<int[]> sum = std::make_unique<int[]>(mysize);
//or if make_unique is not available
std::unique_ptr<int[]> sum(new int[mysize]);

It looks like you have arithmetic series, so you can calculate mysize using equations for the sum of arithmetic progression http://en.wikipedia.org/wiki/Arithmetic_progression#Sum

With std::vector it can be less error-prone, because std::vector can grow, so you can simply push_back() elements inside the loop.

Define sum variable

 std::vector<int> sum;

Then inside the loop instead of sum[k]=i^j; you write

 sum.push_back(i^j);
mip
  • 8,355
  • 6
  • 53
  • 72