overaligned.cc 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright (C) 2016-2022 Free Software Foundation, Inc.
  2. //
  3. // This file is part of the GNU ISO C++ Library. This library is free
  4. // software; you can redistribute it and/or modify it under the
  5. // terms of the GNU General Public License as published by the
  6. // Free Software Foundation; either version 3, or (at your option)
  7. // any later version.
  8. // This 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
  11. // GNU General Public License for more details.
  12. // You should have received a copy of the GNU General Public License along
  13. // with this library; see the file COPYING3. If not see
  14. // <http://www.gnu.org/licenses/>.
  15. // { dg-options "-faligned-new" }
  16. // { dg-do run { target c++11 } }
  17. // { dg-require-cstdint "" }
  18. #include <ext/malloc_allocator.h>
  19. #include <cstddef>
  20. #include <cstdint>
  21. #include <testsuite_hooks.h>
  22. constexpr std::size_t align = alignof(std::max_align_t) * 2;
  23. struct X {
  24. alignas(align) char c;
  25. };
  26. void
  27. test01()
  28. {
  29. __gnu_cxx::malloc_allocator<X> a;
  30. #if __cplusplus > 201402L && _GLIBCXX_HAVE_ALIGNED_ALLOC
  31. X* p1 = a.allocate(1);
  32. VERIFY( (reinterpret_cast<std::uintptr_t>(p1) % align) == 0 );
  33. a.deallocate(p1, 1);
  34. X* p2 = a.allocate(20);
  35. VERIFY( (reinterpret_cast<std::uintptr_t>(p2) % align) == 0 );
  36. a.deallocate(p2, 20);
  37. #else
  38. // Allocating for extended alignment is unreliable without aligned_alloc()
  39. try
  40. {
  41. X* p1 = a.allocate(1);
  42. VERIFY( (reinterpret_cast<std::uintptr_t>(p1) % align) == 0 );
  43. a.deallocate(p1, 1);
  44. }
  45. catch (const std::bad_alloc&)
  46. { }
  47. try
  48. {
  49. X* p2 = a.allocate(20);
  50. VERIFY( (reinterpret_cast<std::uintptr_t>(p2) % align) == 0 );
  51. a.deallocate(p2, 20);
  52. }
  53. catch (const std::bad_alloc&)
  54. { }
  55. #endif
  56. }
  57. int
  58. main()
  59. {
  60. test01();
  61. }