c++invalid-pointer

Invalid pointer after a call to delete


I have this simple code in a file called virtual.cpp:

#include <iostream>


class Parent
{
    public:
    virtual ~Parent(){ std::cout << "Parent Destructor" << std::endl; }

    virtual void VirtualFunction()
    {
        std::cout << "VirtualFunctionInParent" << std::endl;
    }
};

class Child: public Parent
{
    public:
    virtual ~Child() { std::cout << "Child Destructor" << std::endl; }
    virtual void VirtualFunction()
    {
        std::cout << "VirtualFunctionInChild" << std::endl;
    }    
};

int main()
{
    Child child1;
    Parent *parent1 = &child1;
    delete parent1;

}

It compiles correctly

g++ -Wall --pedantic -o virtual virtual.cpp 

But when I run it, I obtain this error:

./virtual 
Child Destructor
Parent Destructor
free(): invalid pointer
Annullato (core dump creato)

I think it is due to the fact that I delete the pointer parent1, so this erases the memory to which the pointer point, namely &child1. So, when child1 goes out of scope, the Child destructor try to deallocate memory which no longer exists.

My questions:

  1. is my reasoning correct?
  2. if my reasoning is correct, which is the correct way to handle this "going out of scope" situation?

Solution

  • I delete the pointer parent1, so this erases the memory to which the pointer point. Is my reasoning correct?

    No. You are getting a core dump from your delete.

    Only addresses returned from new may be passed to delete.

    delete does not erase memory, as memory has no concept of an "erased" state.

    which is the correct way to handle this "going out of scope" situation?

    Remove the delete line. It is not necessary.

    Any variable created within a scope is automatically managed when that scope is left.