C struct: consecutive fields without padding?

any_t - any type ( int , struct something , ...).

Consider this structure:

 struct my_struct { any_t val, any_t array[10] } 

If I define a variable v :

 struct my_struct v; 

Is it possible to use &v.val as an array of 11 any_t elements?

 any_t *p = &v.val; f(p[0]); f(p[5]); f(p[10]); 

Is it guaranteed that between val and array ?

no add-on will be added
+4
source share
3 answers

From the C standard alone, it is unsafe to use &v.val as an array of 11 any_t for the following reasons:

  • Standard C allows unnamed internal filling in a structure: C 2011 (N1570) 6.7.2.1 15, "There may be an unnamed addition to a structural object, but not at the beginning." It would be unusual if the C implementation inserted indents between val and array , because alignment requirements did not require this, but it is allowed, and in some cases it is probably useful, for example, to make array better aligned in performance (and not by necessity )
  • Even if there was a guarantee that the interval between the val and array elements was the same as the array of 11 any_t , there is no guarantee that pointer arithmetic works. C 2011 (N1570) 6.5.6 8 defines pointer arithmetic (including indexing an array), and this only requires arithmetic to work inside the array (including one conditional element at the end). Some implementations of C use basic and biased addressing. In such cases, the base address for val may not support the offsets that apply to array .
  • Even if the C implementation uses normal addressing, its optimizer is allowed to do the deductions based on the C standard. The optimizer can theoretically see that the pointer is obtained from the address val and therefore cannot (in accordance with the C standard) be used to address anything in array . For example, if you did any_t *p = &v.val; p[i] = 3; v.array[j] = 4; any_t *p = &v.val; p[i] = 3; v.array[j] = 4; , the optimizer can treat the v.array[j] and p[i] assignments as independents and execute them in any order, even if you can set i and j to point to the same element.
+7
source

No, nothing is guaranteed by the standard. However, your particular compiler implementation may, of course, guarantee guarantees beyond those made by the standard. Check all documentation.

+1
source

Well, your structure definition is about 2 fields, so your interlocutor cannot use it as 11 elements, so you will need to fill in your fields as they will be reduced.

0
source

Source: https://habr.com/ru/post/1492708/


All Articles