Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Heap Corruption Detected in diamond problem

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading