Memory Bug in C++: Virtual Functions and Pointer Arithmetic

🛑 Can you spot the memory bug? Most of us think we understood object layout, but this snippet hides a "silent killer." 💣 class Test { public:    int a; int b;    virtual void fun() {} // The "Hidden" Player    Test(int t1, int t2) : a(t1), b(t2) {} }; int main() {    Test obj(5, 10);    int* pInt = (int*)&obj;   *(pInt + 0) = 100; // Guess what happens here?    *(pInt + 1) = 200;  cout << obj.a;  } 🧠 The Reality Check We might expect obj.a to print 100. But it won’t, because of this virtual function, compiler inserts a vPtr at the very start of the object. 💡 The Lesson Virtual keyword doesn't just enable polymorphism, it physically reshapes data in memory. Manual pointer arithmetic on classes is a one-way ticket to undefined behaviour. Have you ever been faced such hidden compiler-injected members? Let’s talk in the comments! 👇 #Cpp #Programming #Coding #SoftwareEngineering

  • No alternative text description for this image

Which compiler puts a padding after a vptr? Could you name it so I can observe?

Like
Reply

Why would compiler insert a vtable if it wasn't instructed to do so?

Like
Reply

It's insane that someone even had to talk about this, to be honest. So many people don't even know how virtual functions work.

Like
Reply

Interesting example. Also worth noting the standard never guarantees the vPtr is at offset 0 — that’s just a common ABI choice. With multiple inheritance you can even end up with multiple vPtrs.

Like
Reply

Vptr doesnt have to be at the beginning. It needs to exist, but its unspecified where, so implementation dependent

Like
Reply

This is still a ub even without virtual keyword

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories