project-navigation
Personal tools

Author Topic: memset(*this,0,sizeof....  (Read 6529 times)

Offline Duke

  • Administrator
  • PHALANX veteran
  • *****
  • Posts: 1037
    • View Profile
memset(*this,0,sizeof....
« on: February 03, 2014, 08:38:48 am »
Cppcheck complains: ERROR using memset on a class that has virtual functions (or similar).

Imho Cppcheck is wrong here. I don't know much about the internals of a compiler, but imho the compiler should keep the function table (and thus the virtuals) well apart from the instance data.

Can anyboy confirm/disconfirm ?

Offline Mattn

  • Administrator
  • PHALANX Commander
  • *****
  • Posts: 4831
  • https://github.com/mgerhardy/vengi
    • View Profile
    • Vengi Voxel Tools
Re: memset(*this,0,sizeof....
« Reply #1 on: February 03, 2014, 12:36:59 pm »
one should not use memset of a class with virtual methods - memset would override the vtable, too.

Offline Duke

  • Administrator
  • PHALANX veteran
  • *****
  • Posts: 1037
    • View Profile
Re: memset(*this,0,sizeof....
« Reply #2 on: February 03, 2014, 02:45:08 pm »
then sizeof() must comprise the vtable (or at least a ptr to it). But it doesn't afaik.

Offline Sandro

  • Squad Leader
  • ****
  • Posts: 240
  • Maintenance guy for UFO:AI 3D engine
    • View Profile
Re: memset(*this,0,sizeof....
« Reply #3 on: February 03, 2014, 02:46:17 pm »
Or overrun the next object in memory, since vtbl link in some compilers uses negative offsets. And I've did not start talking about multiple inheritance classes ...

Offline Duke

  • Administrator
  • PHALANX veteran
  • *****
  • Posts: 1037
    • View Profile
Re: memset(*this,0,sizeof....
« Reply #4 on: February 03, 2014, 05:37:27 pm »
My point is that it simply doesn't make sense to store the vtable ptr with the data.
If the compiler did, an array of 10000 instances of class RainDrop would use up 40k bytes of memory where 4 bytes are enough.

The only exception to that is when you are using RTTI. Then it makes sense. Maybe that's where all the superstition comes from ?

Offline DarkRain

  • Project Coder
  • Captain
  • ***
  • Posts: 746
    • View Profile
Re: memset(*this,0,sizeof....
« Reply #5 on: February 03, 2014, 09:51:28 pm »
But it does! Where else to store it anyway?

Ultimately it doesn't matter if it makes sense or not (to us), the compiler actually does store the vtable pointer with the data. (hidden class member), so yeah, don't do it.