flexmember.h 2.6 KB

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