segmentation fault

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];
}
It could be n is lower than 8.
Lines 5-12 will fail if n is less than 7.
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.
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
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?
yes
What is the 'n'?
I have a problem if I pass char in 'n'
n it's an int
Are you sure the segmentation fault is happening inside this function? Even if it is, it might not be what is causing it.
yes, I'm sure
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];
}
thank you
Topic archived. No new replies allowed.