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