Search code examples
c++visual-studio-2008methodsvirtualmemory-address

VSC++, virtual method at bad address, curious bug


This guy:

virtual phTreeClass* GetTreeClass() const { return (phTreeClass*)m_entity_class; }

When called, crashed the program with an access violation, even after a full recompile. All member functions and virtual member functions had correct memory addresses (I hovered mouse over the methods in debug mode), but this function had a bad memory address: 0xfffffffc.

Everything looked okay: the 'this' pointer, and everything works fine up until this function call. This function is also pretty old and I didn't change it for a long time. The problem just suddenly popped up after some work, which I commented all out to see what was doing it, without any success.

So I removed the virtual, compiled, and it works fine. I add virtual, compiled, and it still works fine! I basically changed nothing, and remember that I did do a full recompile earlier, and still had the error back then.

I wasn't able to reproduce the problem. But now it is back. I didn't change anything. Removing virtual fixes the problem.


Solution

  • Don't ever use C-style casts with polymorphic types unless you're seriously sure of what you're doing. The overwhelming probability is that you cast it to a type that it wasn't. If your pointers don't implicitly cast (because they cast to a base class, which is safe) then you're doing it wrong.