1 /* Sizes of structs with flexible array members. 2 3 Copyright 2016-2019 Free Software Foundation, Inc. 4 5 This program is free software: you can redistribute it and/or modify 6 it under the terms of the GNU Lesser General Public License as published by 7 the Free Software Foundation; either version 2.1 of the License, or 8 (at your option) any later version. 9 10 This program is distributed in the hope that it will be useful, 11 but WITHOUT ANY WARRANTY; without even the implied warranty of 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 GNU Lesser General Public License for more details. 14 15 You should have received a copy of the GNU Lesser General Public License 16 along with this program. If not, see <https://www.gnu.org/licenses/>. 17 18 Written by Paul Eggert. */ 19 20 #include <stddef.h> 21 22 /* Nonzero multiple of alignment of TYPE, suitable for FLEXSIZEOF below. 23 On older platforms without _Alignof, use a pessimistic bound that is 24 safe in practice even if FLEXIBLE_ARRAY_MEMBER is 1. 25 On newer platforms, use _Alignof to get a tighter bound. */ 26 27 #if !defined __STDC_VERSION__ || __STDC_VERSION__ < 201112 28 # define FLEXALIGNOF(type) (sizeof (type) & ~ (sizeof (type) - 1)) 29 #else 30 # define FLEXALIGNOF(type) _Alignof (type) 31 #endif 32 33 /* Yield a properly aligned upper bound on the size of a struct of 34 type TYPE with a flexible array member named MEMBER that is 35 followed by N bytes of other data. The result is suitable as an 36 argument to malloc. For example: 37 38 struct s { int n; char d[FLEXIBLE_ARRAY_MEMBER]; }; 39 struct s *p = malloc (FLEXSIZEOF (struct s, d, n * sizeof (char))); 40 41 FLEXSIZEOF (TYPE, MEMBER, N) is not simply (sizeof (TYPE) + N), 42 since FLEXIBLE_ARRAY_MEMBER may be 1 on pre-C11 platforms. Nor is 43 it simply (offsetof (TYPE, MEMBER) + N), as that might yield a size 44 that causes malloc to yield a pointer that is not properly aligned 45 for TYPE; for example, if sizeof (int) == alignof (int) == 4, 46 malloc (offsetof (struct s, d) + 3 * sizeof (char)) is equivalent 47 to malloc (7) and might yield a pointer that is not a multiple of 4 48 (which means the pointer is not properly aligned for struct s), 49 whereas malloc (FLEXSIZEOF (struct s, d, 3 * sizeof (char))) is 50 equivalent to malloc (8) and must yield a pointer that is a 51 multiple of 4. 52 53 Yield a value less than N if and only if arithmetic overflow occurs. */ 54 55 #define FLEXSIZEOF(type, member, n) \ 56 ((offsetof (type, member) + FLEXALIGNOF (type) - 1 + (n)) \ 57 & ~ (FLEXALIGNOF (type) - 1)) 58