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 causing array better aligned performance (rather necessity).
  • even if there guarantee spacing of val , array elements same array of 11 any_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 address val might fail support offsets extend array.
  • 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 in array. e.g., if did any_t *p = &v.val; p[i] = 3; v.array[j] = 4;, optimizer may treat assignments v.array[j] , p[i] independent , perform them in order, though may have set i , j point same element.

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -