Search code examples
c++pointersmemorypolymorphismheap-memory

Invalid address specified to RtlValidateHeap when deleting pointer to derived class


I have a problem with polymorphism in a C++ project I'm working on. I have a base class named State, and a derived TestState class. I'm trying to call a virtual function overidden in the derived class from a State pointer. The virtual function is called, but when deleting the pointer I get the following error:

Invalid address specified to RtlValidateHeap( 00FF0000, 0018FD74 )

After searching for other answers I've been able to understand that this means that the heap is corrupted, but none of the solutions I've found have worked for me.

This is the code I'm running:

int main()
{
    TestState test;

    State *state = new State();
    state = &test;

    state->Init();

    delete state; 
}

State.h

#pragma once

#include <iostream>

class State
{
public:
    State();
    virtual ~State();

    virtual void Init();
    virtual void Reinit();
    virtual void Deinit();
};

State.cpp

#include "State.h"

State::State()
{
}

State::~State()
{
    std::cout << "Destroying State!" << std::endl;
}

void State::Init()
{
    std::cout << "Initialized State!" << std::endl;
}

void State::Deinit()
{
}

void State::Reinit()
{
}

TestState.h

#pragma once
#include "State.h"
#include <iostream>

class TestState : public State
{
public:
    TestState();
    ~TestState();

    void Init();
    void Deinit();
    void Reinit();
};

TestState.cpp

#include "TestState.h"

TestState::TestState()
{
}

TestState::~TestState()
{
    std::cout << "Destroying TestState!" << std::endl;
}

void TestState::Init()
{
    std::cout << "Initialized TestState!" << std::endl;
}

void TestState::Deinit()
{
}

void TestState::Reinit()
{
}

The destructor of both State and TestState are called when the pointer is deleted.

Thanks in advance.


Solution

  • Because you are deleting something in the stack. When you assign the pointer to a reference to a local variable you assign the pointer to an entity allocated in the stack. It cannot be delete using "delete" which is for heap variables. In addition you are leaking what you allocated with the new.

        TestState test;
    
        State *state = new State();
        state = &test; //Now it points to the test which is in the stack
    
        state->Init();
    
        delete state; //Delete something in the stack. Not good.
    

    Something like this should work better.

       TestState test;
    
       State *state = &test;
    
       state->Init();