https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66308

--- Comment #3 from Jonathan Wakely <redi at gcc dot gnu.org> ---
When accessing the member of the derived type (which is actually misaligned):

struct node_base {
  char c;
};

struct node : node_base {
  long long l;
};

int main()
{
  unsigned char* buf = new unsigned char[sizeof(node)+1];
  node_base* n = (node_base*)(buf+1);
  static_cast<node*>(n)->l = 0;
}

GCC complains when the object is in heap memory (but not on the stack):

ubc.cc:13:31: runtime error: member access within misaligned address
0x000001c4ac21 for type 'struct node', which requires 8 byte alignment
0x000001c4ac21: note: pointer points here
 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00
00 00  d1 03 02 00 00
              ^

But not as much as Clang does:


ubc.cc:13:3: runtime error: downcast of misaligned address 0x00000269b011 for
type 'node', which requires 8 byte alignment
0x00000269b011: note: pointer points here
 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00
00 00  e1 0f 02 00 00
              ^ 
ubc.cc:13:26: runtime error: member access within misaligned address
0x00000269b011 for type 'node', which requires 8 byte alignment
0x00000269b011: note: pointer points here
 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00
00 00  e1 0f 02 00 00
              ^ 
ubc.cc:13:26: runtime error: store to misaligned address 0x00000269b019 for
type 'long long', which requires 8 byte alignment
0x00000269b019: note: pointer points here
 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  e1 0f 02 00 00 00
00 00  00 00 00 00 00
              ^ 


I don't know ow many of these extra errors from clang are useful here, but for
the previous two cases the cast is undefined behaviour (the misaligned address
means the node_base* cannot point to a subobject of a node) and so there should
be some ubsan error.

Reply via email to