Reputation: 113
I'm writing a programme with two classes:
class Sequence {
protected:
vector<int> seq_;
public:
Sequence(){
for(int i=0; i<16;i++)
seq_.push_back(0);
};
Sequence(int a, int b,int c){
for(int i=0; i<16; i++)
seq_.push_back(a*i+b*i*i+c*i*i*i);
};
Sequence(const Sequence & myseq){
for(int i=0; i<16;i++)
seq_[i]=myseq.Get_i(i);
};
int Get_i(int i)const{
return seq_[i];
};
void Print() const {
for(int i=0; i<16; i++)
cout<<seq_[i]<<endl;
};
int operator*(Sequence & myseq) const {
int sum=0;
for(int i=0; i<16;i++)
sum+=seq_[i]*myseq.seq_[i];
return sum;
};
void operator=(Sequence & myseq) {
for(int i=0; i<16; i++)
seq_[i]=myseq.seq_[i];
};
};
This first class is devoted to containing a sequence and overloading some basics operators. The following, on the other side, contains a binary sequence corresponding to a number (or a random binary sequence if the default constructor gets the call).
class Binary : public Sequence {
private:
public:
Binary(){
for(int i=0; i<16; i++)
seq_.push_back(round(drand48()));
};
Binary(int num){
double prec=num; double last=0;
for(int i=16; i>=0; i--){
prec=prec-last;
if(int(prec/pow(2,i))==0){
seq_.push_back(0);
last=0;
}else{
seq_.push_back(1);
last=pow(2,i);
}
}
};
Binary not_ () {
Binary mybin;
for(int i=0; i<16; i++){
if( seq_[i]==1){
mybin.seq_[i]=0;
}else{
mybin.seq_[i]=1;
};
};
return mybin;
};
int cost (Sequence myseq){
int k=myseq*(*this)-(Binary::not_())*myseq;
return k;
};
};
The problem is that I get a Segmentation Fault just defining a vector:
vector<Binary> mybins (pow(2,16));
I ran GDB and it stuck at the copy constructor:
Sequence(const Sequence & )
I was wondering if you could give me any help to find the error and to explain it to me. I'm guessing it has something to do with my poor knowledge of how the standard library works! Thank you for your time.
Upvotes: 0
Views: 75
Reputation: 118350
Sequence(const Sequence & myseq){
This is a constructor. It is constructing a new object.
for(int i=0; i<16;i++)
seq_[i]=myseq.Get_i(i);
The seq_
member is an initially empty vector. Attempting to set nonexistent values in the vector is undefined behavior, and the reason for your crash. Your other constructors use push_back()
, correctly, to insert new values into a vector. This should be done here as well.
Upvotes: 2
Reputation: 171127
All your constructors start with an empty seq_
and correctly use push_back
to grow it and add elements to it ... except for the copy constructor, which also starts with and empty seq_
but uses []
instead. So it's accessing elements which are not in the vector, giving you Undefined Behaviour.
To solve this correctly, remove the copy constructor altogether. The compiler will then generate one for you, which will do just what you need. As a bonus, it will also generate a move constructor.
Upvotes: 0