Merge pull request #2309 from mitza-oci/warnings
[ACE_TAO.git] / ACE / examples / APG / Shared_Memory / Malloc.cpp
blobabad7302c1d7ba796406b15553c5fe43a23db150
1 #include "ace/OS_NS_stdio.h"
2 #include "ace/OS_NS_string.h"
4 // Listing 1 code/ch17
5 #include "ace/MMAP_Memory_Pool.h"
6 #include "ace/Malloc_T.h"
7 #include "ace/Null_Mutex.h"
9 typedef ACE_Malloc<ACE_MMAP_MEMORY_POOL, ACE_Null_Mutex>
10 ALLOCATOR;
11 typedef ACE_Malloc_LIFO_Iterator <ACE_MMAP_MEMORY_POOL,
12 ACE_Null_Mutex>
13 MALLOC_LIFO_ITERATOR;
15 ALLOCATOR *g_allocator;
16 // Listing 1
18 // Listing 2 code/ch17
19 class Record
21 public:
22 Record (int id1, int id2, char *name)
23 : id1_(id1), id2_(id2), name_(0)
25 size_t len = ACE_OS::strlen (name) + 1;
26 this->name_ =
27 reinterpret_cast<char *> (g_allocator->malloc (len));
28 ACE_OS::strcpy (this->name_, name);
31 ~Record () { g_allocator->free (name_); }
32 char* name() { return name_; }
33 int id1 () { return id1_; }
34 int id2 () { return id2_; }
36 private:
37 int id1_;
38 int id2_;
39 char *name_;
41 // Listing 2
42 // Listing 5 code/ch17
43 void showRecords ()
45 ACE_DEBUG ((LM_DEBUG,
46 ACE_TEXT ("The following records were found:\n")));
48 MALLOC_LIFO_ITERATOR iter (*g_allocator);
50 for (void *temp = 0; iter.next (temp) != 0; iter.advance ())
52 Record *record =
53 reinterpret_cast<Record *> (temp);
54 ACE_DEBUG ((LM_DEBUG,
55 ACE_TEXT ("Record name: %C|id1:%d|id2:%d\n"),
56 record->name (),
57 record->id1 (),
58 record->id2 ()));
62 // Listing 5
63 // Listing 3 code/ch17
64 int addRecords ()
66 char buf[32];
68 for (int i = 0; i < 10; i++)
70 ACE_OS::sprintf (buf, "%s:%d", "Record", i);
71 void *memory = g_allocator->malloc (sizeof (Record));
72 if (memory == 0)
73 ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"),
74 ACE_TEXT ("Unable to malloc")),
75 -1);
77 // Allocate and place record
78 Record* newRecord = new (memory) Record (i, i+1, buf);
79 if (g_allocator->bind (buf, newRecord) == -1)
80 ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("%p\n"),
81 ACE_TEXT ("bind failed")),
82 -1);
85 return 0;
87 // Listing 3
88 // Listing 4 code/ch17
89 // Backing file where the data is kept.
90 #define BACKING_STORE ACE_TEXT("backing.store")
92 int ACE_TMAIN (int argc, ACE_TCHAR *[])
94 ACE_NEW_RETURN (g_allocator,
95 ALLOCATOR (BACKING_STORE),
96 -1);
97 if (argc > 1)
99 showRecords ();
101 else
103 addRecords ();
106 g_allocator->sync ();
107 delete g_allocator;
108 return 0;
110 // Listing 4