c - Is this a portable way to make a stack buffer eight-byte aligned? -
struct { uint64_t a; char z[120]; } b; ... struct buffer_with_alignment_requirement* c = (struct buffer_w*)&b; c->start_using_it;
without first member a
, might crash when accessing fields in buffer. portable , correct add member force aligment whole struct strict enough?
this not question pointer aliasing, whether address of b
on stack eight-byte aligned.
it depends on mean aligned. if want (uintptr_t)&b % 8 == 0
, there no portable way obtain this, conversion pointer integer implementation-defined , need not sane, natural mapping.
if want buffer sufficiently aligned access type uint64_t
, solution works well. why don't use (possibly array of) type struct buffer_with_alignment_requirement
, rather ugly union hackery? in other words, give buffer right type intend access begin with. can pass pointer type read
, fread
, revc
, etc. , other functions might using write buffer, , if you'll passing function expects buffer pointer of type char *
or unsigned char *
, can cast when passing it; cast well-defined , valid.
Comments
Post a Comment