2

So, I was playing around with Visual Studio's Test Suite and I discovered something interesting:

I have an instance to class A at address, say, 0x0656a64c. Then when I watched over the variable, it says that its __vfptr is pointing at 0x077e7c0c.

As far as I know, a class' virtual table pointer should be located in the first 4 bytes (or 8 bytes on 64-bit applications) of the class instance, unless it's a case of multiple inheritance (then it's just offsets of the 1st vtable address).

I observed that Visual Studio compiled my test into a .dll and run its test tools dynamically loading the .dll.

Could this be what's causing the address difference?

Here's a screenshot of the VS debugger

Difference in addresses

Ron
  • 14,674
  • 4
  • 34
  • 47
Fireken
  • 118
  • 5

2 Answers2

3

You are confusing the address of the vptr, and the address that the vptr is pointing at. You are (roughly) correct that the usual implementation is that the vptr is the first thing in the object - but Visual Studio is showing you the address of the vtable (which is shared between all objects of the class).

0

This is just normal behavior for MS C++ compiler. 2 DLL's that create instances of the same class objects will have different vtables. Intuition would says the vtable should be shared with all instances regardless of what DLL's code created (new) it. It should be common to the implementation of the class. Not true.

This creates a danger when a DLL is released dynamically. All objects allocated may still be in valid (Process) heap. But, if it has a virtual destructor then that is defined in the vtable. It is now in freed space. So the vtable is corrupt. Any use of it will generate exception.

The solution is to clean up any/all allocations made by the dynamic DLL that might also have a vtable (e.g. virtual destructor) before freeing the DLL. Any allocations made in process heap that dont point to a DLL based vtable are fine. Worste case is a memory leak if not properly tracked.

Menace
  • 1,061
  • 13
  • 15