My simple class A
looks as follows:
class A{
char* seq;
public:
A(std::string seq);
~A();
void printSeq();
};
A::A(std::string& seqstr ){
this->seq = new char[strlen(seqstr.c_str())+1]();
strcpy(seq, seqstr.c_str());
}
A::~A(){
delete[] this->seq;
}
A::printSeq(){
for(int i=0; i<strlen(seq);i++){
std::cout << seq[i];
}
std::cout << std::endl;
}
This when called as follows, results in an error.
const char *args[] = {"foo", "bar", "blah", "blahblah"};
std::vector<std::string> x(args, std::end(args));
std::vector<A> avec;
for(int i=0;i<x.size(); i++){
avec.push_back( A( x[i] ) );
avec[i].printSeq();
}
The error is as follows:
foo malloc: * error for object 0x7fea78610930: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug Abort trap: 6
I am not quite sure what causes this error. What is confusing to me is that 1) we do create a dynamic array here, and 2) and copy the elements of the input string. Is this a scope issue? I would appreciate any help in resolving this.