[英]Segmentation Fault: 11 on small input for array/vector
There are several questions related to this error on stackoverflow, and I understand that its related to excess memory usage by the array, or when using pointers (I tried this with vectors aswell) but using a small array, it still shows this error. 与stackoverflow上的此错误有关的几个问题,我了解到它与数组过多的内存使用有关,或者与使用指针(我也对向量使用过)有关,但使用较小的数组时,它仍然显示此错误。 The same code earlier was running fine (for merge sorting an array). 之前的相同代码运行良好(用于对数组进行合并排序)。
My input was as follows: 我的输入如下:
5 5
9 8 1 2 4 9 8 1 2 4
Output: 输出:
Segmentation fault: 11 细分错误:11
#include<iostream>
#include<vector>
using namespace std;
void merge(vector <int> ar, int l, int m, int r){
int n1 = m-l+1;
int n2 = r-m;
int L[n1];
int R[n2];
for (int i = 0; i < n1; ++i)
{
L[i]=ar[l+i];
}
for (int j = 0; j < n2; ++j)
{
R[j]=ar[m+j+1];
}
int i,j;
i = j = 0;
int k = i;
while(i<n1 && j<n2){
if (L[i]<R[j])
{
ar[k]=L[i];
i++;
}
else if (R[j]<L[i])
{
ar[k]=R[j];
j++;
}
k++;
}
while(i<n1){
ar[k]=L[i];
i++;
k++;
}
while(j<n2){
ar[k]=R[j];
j++;
k++;
}
}
void mergesort(vector <int> ar, int l, int r){
int m;
m=r+(l-r)/2;
if (l<r)
{
mergesort(ar, l, m);
mergesort(ar, m+1, r);
merge(ar, l, m, r);
}
}
void print(vector <int> ar, int size){
for (int i = 0; i < size; ++i)
{
cout<<ar[i]<< " ";
}
}
int main()
{
int n;
cin>>n;
vector <int> ar;
for (int i = 0; i < n; ++i)
{
cin>>ar[i];
}
print(ar,n);
mergesort(ar, 0, n-1);
print(ar, n);
return 0;
}
The problem is in part with m=r+(lr)/2
. 问题部分在于m=r+(lr)/2
。 When l
is 0
and r
is 1
, (lr)/2
is 0
. 当l
为0
且r
为1
, (lr)/2
为0
。 This makes m
equal to 1
, l
equal to 0
, and r
equal to 1
and the mergesort(ar, l, m);
这使m
等于1
, l
等于0
, r
等于1
,并且mergesort(ar, l, m);
call identical to the one it just worked through. 称其与刚刚通过的相同。 The stack grows unbounded until you have a segmentation fault. 在出现分段错误之前,堆栈将无限增长。 One way to fix this which will also make your code more efficient is to merge the lists when the difference between l
and r
is below some threshold. 解决此问题的一种方法也可以使您的代码更有效,这是当l
和r
之间的差值低于某个阈值时合并列表。 Or, you can just swap the two elements when you get to the point where l
and r
differ by one, like so: 或者,当到达l
和r
相差l
的点时,您可以交换两个元素,如下所示:
if (l - r <= 1) {
int temp = ar[l];
ar[l] = ar[r];
ar[r] = temp;
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.