test_bug_2696.cpp 2.2 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 #2696 (https://svn.boost.org/trac/boost/ticket/2696)
  8. #include <boost/pool/pool.hpp>
  9. #include <boost/detail/lightweight_test.hpp>
  10. struct limited_allocator_new_delete
  11. {
  12. typedef std::size_t size_type;
  13. typedef std::ptrdiff_t difference_type;
  14. static char * malloc BOOST_PREVENT_MACRO_SUBSTITUTION(const size_type bytes)
  15. {
  16. #ifndef BOOST_POOL_VALGRIND
  17. static const unsigned max_size = sizeof(void*) * 40 + boost::integer::static_lcm<sizeof(size_type), sizeof(void *)>::value + sizeof(size_type);
  18. #else
  19. static const unsigned max_size = sizeof(void*) * 40;
  20. #endif
  21. if(bytes > max_size)
  22. return 0;
  23. return new (std::nothrow) char[bytes];
  24. }
  25. static void free BOOST_PREVENT_MACRO_SUBSTITUTION(char * const block)
  26. {
  27. delete [] block;
  28. }
  29. };
  30. int main()
  31. {
  32. static const unsigned alloc_size = sizeof(void*);
  33. boost::pool<limited_allocator_new_delete> p1(alloc_size, 10, 40);
  34. for(int i = 1; i <= 40; ++i)
  35. BOOST_TEST((p1.ordered_malloc)(i));
  36. BOOST_TEST(p1.ordered_malloc(42) == 0);
  37. //
  38. // If the largest block is 40, and we start with 10, we get 10+20+40 elements before
  39. // we actually run out of memory:
  40. //
  41. boost::pool<limited_allocator_new_delete> p2(alloc_size, 10, 40);
  42. for(int i = 1; i <= 70; ++i)
  43. BOOST_TEST((p2.malloc)());
  44. boost::pool<limited_allocator_new_delete> p2b(alloc_size, 10, 40);
  45. for(int i = 1; i <= 100; ++i)
  46. BOOST_TEST((p2b.ordered_malloc)());
  47. //
  48. // Try again with no explicit upper limit:
  49. //
  50. boost::pool<limited_allocator_new_delete> p3(alloc_size);
  51. for(int i = 1; i <= 40; ++i)
  52. BOOST_TEST((p3.ordered_malloc)(i));
  53. BOOST_TEST(p3.ordered_malloc(42) == 0);
  54. boost::pool<limited_allocator_new_delete> p4(alloc_size, 10);
  55. for(int i = 1; i <= 100; ++i)
  56. BOOST_TEST((p4.ordered_malloc)());
  57. boost::pool<limited_allocator_new_delete> p5(alloc_size, 10);
  58. for(int i = 1; i <= 100; ++i)
  59. BOOST_TEST((p5.malloc)());
  60. return boost::report_errors();
  61. }