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