test_bug_1252.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* Copyright (C) 2011 John Maddock
  2. *
  3. * Use, modification and distribution is subject to the
  4. * Boost Software License, Version 1.0. (See accompanying
  5. * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
  6. */
  7. // Test of bug #1252 (https://svn.boost.org/trac/boost/ticket/1252)
  8. #include <boost/pool/pool.hpp>
  9. #include <boost/detail/lightweight_test.hpp>
  10. #include <boost/type_traits/alignment_of.hpp>
  11. #include <cstring>
  12. struct limited_allocator_new_delete
  13. {
  14. typedef std::size_t size_type;
  15. typedef std::ptrdiff_t difference_type;
  16. static char * malloc BOOST_PREVENT_MACRO_SUBSTITUTION(const size_type bytes)
  17. {
  18. if(bytes > 1510 * 32)
  19. return 0;
  20. return new (std::nothrow) char[bytes];
  21. }
  22. static void free BOOST_PREVENT_MACRO_SUBSTITUTION(char * const block)
  23. {
  24. delete [] block;
  25. }
  26. };
  27. template <class T>
  28. void test_alignment(T)
  29. {
  30. unsigned align = boost::alignment_of<T>::value;
  31. boost::pool<> p(sizeof(T));
  32. unsigned limit = 100000;
  33. for(unsigned i = 0; i < limit; ++i)
  34. {
  35. void* ptr = (p.malloc)();
  36. BOOST_TEST(reinterpret_cast<std::size_t>(ptr) % align == 0);
  37. // Trample over the memory just to be sure the allocated block is big enough,
  38. // if it's not, we'll trample over the next block as well (and our internal housekeeping).
  39. std::memset(ptr, 0xff, sizeof(T));
  40. }
  41. }
  42. int main()
  43. {
  44. boost::pool<limited_allocator_new_delete> po(1501);
  45. void* p = (po.malloc)();
  46. BOOST_TEST(p != 0);
  47. test_alignment(char(0));
  48. test_alignment(short(0));
  49. test_alignment(int(0));
  50. test_alignment(long(0));
  51. test_alignment(double(0));
  52. test_alignment(float(0));
  53. test_alignment((long double)(0));
  54. #ifndef BOOST_NO_LONG_LONG
  55. test_alignment((long long)(0));
  56. #endif
  57. return boost::report_errors();
  58. }