[cfe-dev] Safe use of offsetof?

Jeffrey Walton noloader at gmail.com
Tue Sep 17 12:23:58 PDT 2013


I'm working with some source code that does the following. Its
declared as a static method.

167  long
168  cbdata::MakeOffset()
169  {
170      cbdata *zero = (cbdata *)0L;
171      void **dataOffset = &zero->data;
172      return (long)dataOffset;
173  }

Under UBSan, the code creates an entry for each use of MakeOffset():

    runtime error: member access within null pointer of type 'cbdata'

The code is not amicable to use of offsetof(...). I think its because
there's a Stack member, but I don't know the C/C++ language rules like
most folks.

   cbdata.cc:176:19: error: offset of on non-POD type 'struct cbdata'

But I'm fairly certain (correct me here) it falls under case 2 listed
at http://gcc.gnu.org/ml/gcc/2003-11/msg00281.html:

    2) Those cases where any reasonable implementation (and all
       implementations we know of) give the right answer, but ISO
       C++ says "undefined".

Is there a way to code MakeOffset() so that UBSan will be happy so as
to avoid the runtime error? Or will this have to go into an ignore
list?

Thanks in advance.



More information about the cfe-dev mailing list