C struct: consecutive fields without padding? -
any_t
type (int
, struct something
, …).
consider structure:
struct my_struct { any_t val, any_t array[10] }
if define variable v
:
struct my_struct v;
is safe use &v.val
array of 11 any_t
items?
any_t *p = &v.val; f(p[0]); f(p[5]); f(p[10]);
is guaranteed no padding added between val
, array
?
from c standard alone, not safe use &v.val
array of 11 any_t
these reasons:
- the c standard permits unnamed internal padding in struct: c 2011 (n1570) 6.7.2.1 15, “there may unnamed padding within structure object, not @ beginning.” unusual c implementation insert padding between
val
,array
, because alignment requirements not require it, permitted , conceivably beneficial in circumstances, such causingarray
better aligned performance (rather necessity). - even if there guarantee spacing of
val
,array
elements same array of 11any_t
, there no guarantee pointer arithmetic works. c 2011 (n1570) 6.5.6 8 defines pointer arithmetic (including array indexing), , requires arithmetic work within array (including 1 notional element @ end). c implementations use base-and-offset addressing. in such cases, base addressval
might fail support offsets extendarray
. - even if c implementation uses normal addressing, optimizer permitted make deductions based on c standard. optimizer can, in theory, see pointer derived address of
val
, therefore cannot (in accordance c standard) used address inarray
. e.g., if didany_t *p = &v.val; p[i] = 3; v.array[j] = 4;
, optimizer may treat assignmentsv.array[j]
,p[i]
independent , perform them in order, though may have seti
,j
point same element.
Comments
Post a Comment