-5
 struct base
 {
     int num;
     char ch;
     float fl;
 };

 struct ss : virtual base
 {
 };

 void main()
 {
     ss sa;

     sa.num = 100;

     cout << sa.num << endl;

     memset(&sa, 0, sizeof(sa));        // set all members to zero

     cout <<  sa.num << endl;           // Access violation reading location 0x00000004.


 }

I can access members from a struct that is derived from a virtual base. When zeroing out the struct it also causes the lost of access to the members. Does this mean we would have to clear members individually instead of using memset or ZeroMemory?

user3613229
  • 101
  • 4

1 Answers1

5

Short answer: Undefined behaviour. Full stop.

Long answer: base is a virtual base of ss. Thus, it is unknown at compile time at which offset from the beginning of ss the parent base is located. This offset information must be retrieved at runtime. The information is stored in the vtable of the object.

So in order to know the offset of fields in base, the vtable pointer (which resides inside the object) has to be considered. You just nulled this vtable pointer by nulling the whole struct. So when it is dereferenced to look up the offset, everything is about to blow up. The offset of base seems to be at offset 4 from the beginning of the vtable, this is why you get an access violation at address 4.

gexicide
  • 38,535
  • 21
  • 92
  • 152