This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: PODs vs memset


Paolo Carlini wrote:

> ... restricting now the attention to "scalars" (i.e., what our
> library __is_scalar implements, no member pointers), I still think it
> makes sense to use memset elsewhere too, not only in valarray...

<delurk/>
Be careful with memset-ing PODs as a matter of policy.

Generally, it is safe to memset PODs passed by value, but not by
reference.  The problem case is a derived class with a POD base - in
this situation you are no longer allowed to memset the POD, and if you
pass a derived object to a function taking base by reference (which the
called-function cannot know) then you hit undefined behaviour.

When if that UB likely to be a problem?  When the derived object packs
members into the 'dead space' at the end of the POD - although I am not
sure if the GCC ABI allows this or not.

Test case might be something like:

struct base {
  short s1;
};

struct derived : base {
 short s2;
}


void test( base & b ) {
  memset( &b, 0, sizeof( b ) );
}

int main()
{
  derived d;
  d.s1 = 13;
  d.s2 = 42;
  test( d );
  assert( d.s1 == 0 );
  assert( d.s2 == 42 );
}

<lurk/>

-- 
AlisdairM


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]