I use virtual inheritance to solve the diamond problem. The code crashes after calling the destructor of the base class A with the "Heap corruption detected" error:
#include <cstring>
class A
{
char* name;
public:
A(const char* name)
{
int len = strlen(name) + 1;
this->name = new char[len];
strncpy(this->name, name, len)[len] = '\0';
}
virtual ~A()
{
delete[] this->name;
}
};
class B : virtual public A
{
public:
B(const char* name) : A(name) {}
virtual ~B() {}
};
class C : virtual public A
{
public:
C(const char* name) : A(name) {}
virtual ~C() {}
};
class D : public B, public C
{
public:
D(const char* name) : A(name), B(name), C(name) {}
virtual ~D() {}
};
int main()
{
D d("qwerty");
}
Any ideas?
>Solution :
Change:
strncpy(this->name, name, len)[len] = '\0';
to:
strncpy(this->name, name, len);
Your [len] is accessing one past the end of your array, and strncpy already copies the terminating '\0'.