2 tre-mem.c - TRE memory allocator
4 This software is released under a BSD-style license.
5 See the file LICENSE for details and copyright.
10 This memory allocator is for allocating small memory blocks efficiently
11 in terms of memory overhead and execution speed. The allocated blocks
12 cannot be freed individually, only all at once. There can be multiple
18 #endif /* HAVE_CONFIG_H */
22 #include "tre-internal.h"
27 /* Returns a new memory allocator or NULL if out of memory. */
29 tre_mem_new_impl(int provided
, void *provided_block
)
35 memset(mem
, 0, sizeof(*mem
));
38 mem
= xcalloc(1, sizeof(*mem
));
45 /* Frees the memory allocator and all memory allocated with it. */
47 tre_mem_destroy(tre_mem_t mem
)
49 tre_list_t
*tmp
, *l
= mem
->blocks
;
62 /* Allocates a block of `size' bytes from `mem'. Returns a pointer to the
63 allocated block or NULL if an underlying malloc() failed. */
65 tre_mem_alloc_impl(tre_mem_t mem
, int provided
, void *provided_block
,
66 int zero
, size_t size
)
72 DPRINT(("tre_mem_alloc: oops, called after failure?!\n"));
76 #ifdef MALLOC_DEBUGGING
82 DPRINT(("tre_mem_alloc: xmalloc forced failure\n"));
88 #endif /* MALLOC_DEBUGGING */
92 /* We need more memory than is available in the current block.
93 Allocate a new block. */
97 DPRINT(("tre_mem_alloc: using provided block\n"));
98 if (provided_block
== NULL
)
100 DPRINT(("tre_mem_alloc: provided block was NULL\n"));
104 mem
->ptr
= provided_block
;
105 mem
->n
= TRE_MEM_BLOCK_SIZE
;
110 if (size
* 8 > TRE_MEM_BLOCK_SIZE
)
111 block_size
= size
* 8;
113 block_size
= TRE_MEM_BLOCK_SIZE
;
114 DPRINT(("tre_mem_alloc: allocating new %d byte block\n",
116 l
= xmalloc(sizeof(*l
));
122 l
->data
= xmalloc(block_size
);
130 if (mem
->current
!= NULL
)
131 mem
->current
->next
= l
;
132 if (mem
->blocks
== NULL
)
140 /* Make sure the next pointer will be aligned. */
141 size
+= ALIGN(mem
->ptr
+ size
, long);
143 /* Allocate from current block. */
148 /* Set to zero if needed. */
150 memset(ptr
, 0, size
);