question

unfortunately, my code contains a memory leak. how to remove the leak?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Base
{
public:
virtual void doSomething() = 0;
};
class Derived : public Base
{
public:
virtual void doSomething()
{
// Do the action
}
};
int main(int argc, char[] argv)
{
 Derived* pDerived = new Derived;
Base* pBase = pDerived;
delete pBase;
 return 0;
}
Same answer as here, before you trashed the post to hide your embarrassment.
http://forums.codeguru.com/showthread.php?562863-important&p=2228173

Quoted for posterity.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Base
{
public:
virtual void doSomething() = 0;
};
class Derived : public Base
{
public:
virtual void doSomething()
{
// Do the action
}
};
int main(int argc, char[] argv)
{
 Derived* pDerived = new Derived;
Base* pBase = pDerived;
delete pBase;
 return 0;
}
I think using another forum is not your business, and I can use any website and forum for my questions, If you don't want to help/ if you cannot help, so please be quiet and let another person to consult and help me...
The destructor in class Base is not virtual,
so line 18 delete pBase; engenders undefined behaviour.

Deleting an object through pointer to base invokes undefined behavior unless the destructor in the base class is virtual. ... A common guideline is that
a destructor for a base class must be either public and virtual or protected and nonvirtual
https://en.cppreference.com/w/cpp/language/destructor#Virtual_destructors
Topic archived. No new replies allowed.