Apply patch for [CVE-2012-2677][boost] ordered_malloc() overflow
[external/boost.git] / libs / interprocess / example / doc_managed_heap_memory.cpp
1 //////////////////////////////////////////////////////////////////////////////
2 //
3 // (C) Copyright Ion Gaztanaga 2006-2009. Distributed under the Boost
4 // Software License, Version 1.0. (See accompanying file
5 // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 //
7 // See http://www.boost.org/libs/interprocess for documentation.
8 //
9 //////////////////////////////////////////////////////////////////////////////
10 #include <boost/interprocess/detail/config_begin.hpp>
11 #include <boost/interprocess/detail/workaround.hpp>
12 //[doc_managed_heap_memory
13 #include <boost/interprocess/containers/list.hpp>
14 #include <boost/interprocess/managed_heap_memory.hpp>
15 #include <boost/interprocess/allocators/allocator.hpp>
16 #include <cstddef>
17
18 using namespace boost::interprocess;
19 typedef list<int, allocator<int, managed_heap_memory::segment_manager> > 
20    MyList;
21
22 int main ()
23 {
24    //We will create a buffer of 1000 bytes to store a list
25    managed_heap_memory heap_memory(1000);
26
27    MyList * mylist = heap_memory.construct<MyList>("MyList")
28                         (heap_memory.get_segment_manager());
29
30    //Obtain handle, that identifies the list in the buffer
31    managed_heap_memory::handle_t list_handle = heap_memory.get_handle_from_address(mylist);
32
33    //Fill list until there is no more memory in the buffer
34    try{
35       while(1) {
36          mylist->insert(mylist->begin(), 0);
37       }
38    }
39    catch(const bad_alloc &){
40       //memory is full
41    }
42    //Let's obtain the size of the list
43    std::size_t old_size = mylist->size();
44
45    //To make the list bigger, let's increase the heap buffer
46    //in 1000 bytes more.
47    heap_memory.grow(1000);
48
49    //If memory has been reallocated, the old pointer is invalid, so
50    //use previously obtained handle to find the new pointer.
51    mylist = static_cast<MyList *>
52                (heap_memory.get_address_from_handle(list_handle));
53    
54    //Fill list until there is no more memory in the buffer
55    try{
56       while(1) {
57          mylist->insert(mylist->begin(), 0);
58       }
59    }
60    catch(const bad_alloc &){
61       //memory is full
62    }
63
64    //Let's obtain the new size of the list      
65    std::size_t new_size = mylist->size();
66
67    assert(new_size > old_size);
68
69    //Destroy list
70    heap_memory.destroy_ptr(mylist);
71
72    return 0;
73 }
74 //]
75 #include <boost/interprocess/detail/config_end.hpp>