简体   繁体   中英

C++ inheritance and valgrind memory leak

I was checking my codes with valgrind and it found a memory leak. I didn't understand why it happened. Instead of putting my main code, I made a similar program to check whether my other allocations(char array etc.) cause the problem or classes cause this.

class zoo{
public:
    int x;
    zoo(int a){x = a;};
};

class doo:public zoo{
public:
    int y;
    doo(int a,int b):zoo(a){y = b;};
};

class foo : public doo{
public:
    String z;
    foo(int a, int b, const char *c):doo(a,b){
        z = c;
    };
};

zoo * something(const char * str){
    return (zoo *) new foo(1,2,str);
}
int main() {
    zoo * ex = something("blabla:sometext:blabla:overflow:message");
    cout<<"msg:"<< ((foo*)ex)->z<<endl;
    delete ex;
    return 0;
}

Nothing fancy in the code. There are base classes and I want to get a pointer in the last class as the pointer of the first base class.

When I compile this valgrind shows 4 allocs 3 frees.

What is wrong with this code ? Perhaps I misunderstood the concept of inheritance. Yet when I call the something function as

something("blabla")

No error is printed.

As the base class has no virtual destructor then in this statement

delete ex;

there is called only the destructor of the class zoo according to the static type of the pointer. Sub-objects of the object of the type foo created in this statement

return (zoo *) new foo(1,2,str);

are not destructed.

You could at least define the destructor in the class zoo like

class zoo{
public:
    int x;
    zoo(int a){x = a;};
    virtual ~zoo() = default;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM