[try Beta version]
Not logged in

 
segmentation fault

Nov 9, 2016 at 8:26am
I don't know why is a segmentation fault error in my code .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 int nbSeqRugbyDyn(int n) {
    std::vector<int> t;
  for (int i=0; i<=n; i++) t.push_back(i);
    
    t[0]=1;
    t[1]=0;
    t[2]=0;
    t[3]=2;
    t[4]=0;
    t[5]=1;
    t[6]=4;
    t[7]=1;
    for(int i=8;i<n;i++){
        t[i]=t[i-7]+t[i-5]+2*t[i-3];
    }
    return t[n];
}
Nov 9, 2016 at 8:31am
It could be n is lower than 8.
Nov 9, 2016 at 8:36am
Lines 5-12 will fail if n is less than 7.
Nov 9, 2016 at 8:39am
If n is less than 7, this line will cause segmentation fault :
t[7] = 1;

When n is 6, the vector has 7 elements. The element t[7] does not exist.
Nov 9, 2016 at 8:42am
int nbSeqRugbyDyn(int n) {
std::vector<int> t;
for (int i=0; i<=n; i++) t.push_back(i);
if(n==0)
return 1;
else
if(n==1)
return 0;
else
if(n==2)
return 0;
else
if(n==3)
return 2;
else
if(n==4)
return 0;
else
if(n==5)
return 1;
else
if(n==6)
return 4;
else
if(n==7)
return 1;
else
for(int i=8;i<n;i++){
t[i]=t[i-7]+t[i-5]+2*t[i-3];
}
return t[n];
}


still have the same problem
Nov 9, 2016 at 8:44am
How about :
1
2
3
4
5
int nbSeqRugbyDyn(int n) {
std::vector<int> t;
for (int i=0; i<=n; i++) t.push_back(i);
return t[n];
}


Are you still having the same problem?
Nov 9, 2016 at 8:46am
yes
Nov 9, 2016 at 8:51am
What is the 'n'?
I have a problem if I pass char in 'n'
Nov 9, 2016 at 8:52am
n it's an int
Nov 9, 2016 at 8:59am
Are you sure the segmentation fault is happening inside this function? Even if it is, it might not be what is causing it.
Nov 9, 2016 at 9:00am
yes, I'm sure
Nov 9, 2016 at 9:13am
The simpliest solution would be usin max(...) to adjust the vector capacity:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 int nbSeqRugbyDyn(int n) {
    std::vector<int> t;
int n1 = std::max(n, 8); // Note: n1
  for (int i=0; i<=n1; i++) t.push_back(i); // Note: use n1 here
    
    t[0]=1;
    t[1]=0;
    t[2]=0;
    t[3]=2;
    t[4]=0;
    t[5]=1;
    t[6]=4;
    t[7]=1;
    for(int i=8;i<n;i++){
        t[i]=t[i-7]+t[i-5]+2*t[i-3];
    }
    return t[n];
}
Nov 9, 2016 at 9:15am
thank you
Topic archived. No new replies allowed.