I have a msg class which holds a char* and its size basically. And sometimes I get a SIGABRT when deleting my char* and I can't figure out why!
class MSG
{
private:
char* data;
public:
std::size_t size;
std::string target_id;
MSG( const MSG& msg ) : MSG( msg.getData(), msg.size, msg.target_id )
{ };
MSG( char* sourceData, std::size_t sourceSize, const std::string& id )
{
data = new char[sourceSize];
std::copy_n( sourceData, sourceSize, data );
size = sourceSize;
target_id = id;
};
MSG( ) : MSG( ( char* ) nullptr, 0, UNDEFINED )
{ };
~MSG( )
{
delete[] data;
data = 0;
};
MSG& operator=(MSG& that)
{
swap(*this, that);
return *this;
}
MSG& operator=(const MSG& other)
{
if (this != &other) // (1)
{
// get the new data ready before we replace the old
std::size_t newSize = other.size;
char* newArray = newSize ? new char[newSize]() : nullptr; // (3)
std::copy(other.getData(), other.getData() + newSize, newArray); // (3)
// replace the old data (all are non-throwing)
delete [] data;
size = newSize;
data = newArray;
target_id = other.target_id;
}
return *this;
}
};
When debugging I get this output which leads to the error:
data = {char} 0 '\000'
size = 2
I really don't know what's wrong here...
Update: In terminal I get more info: double free or corruption
2nd Update: Added copy constructor
3rd update: Added assignment operators