Nikolay Vyahhi
Nikolay Vyahhi

Reputation: 1482

memcpy for class-level array in copy constructor leads to segfault

There is a template class for sequences in 4-letter alphabet (=> 2 bits per letter):

template <size_t _size>
class Seq {
private:
    const static size_t _byteslen = (_size / 4) + (_size % 4 != 0);
    char _bytes[_byteslen];
public:
    Seq() {};
    Seq(const char* s);
    Seq(const Seq<_size> &seq);
    ...
    std::string str() const;
    ...
}

If copy constructor is implemented as silly from-to-string, then everything works OK.

Seq(const Seq<_size> &seq) {
    Seq(seq.str().c_str());
}

Otherwise, if copy constructor uses memcpy like that:

Seq(const Seq<_size> &seq) {
    memcpy(_bytes, seq._bytes, _byteslen);
}

The program gets segfault few seconds later (doing += or [] operations with totally different std::string). What can be a problem with such memcpy? Thank you.

P.S. memmove doesn't help.

Upvotes: 2

Views: 812

Answers (2)

Bo Persson
Bo Persson

Reputation: 92301

Just a guess: your str() function returns _bytes as a string, trying to build that from a buffer that is not nul terminated.

Upvotes: 0

aschepler
aschepler

Reputation: 72421

"If copy constructor is implemented as silly from-to-string, then everything works OK."

Seq(const Seq<_size> &seq) {
    Seq(seq.str().c_str());
}

Really? Because that constructor doesn't initialize _bytes[] at all. (Instead, it creates a different temporary Seq object, which is unused and immediately destroyed.)

Upvotes: 5

Related Questions