void b_trie_insert(b_trie_t *trie, const char *key, void *data) { if (data == NULL || key == NULL) return; b_trie_node_t *parent = NULL; b_trie_node_t *previous; b_trie_node_t *current; b_trie_node_t *tmp; while (1) { if (trie->root == NULL || (parent != NULL && parent->child == NULL)) { current = b_malloc(sizeof(b_trie_node_t)); current->key = *key; current->data = NULL; current->next = NULL; current->child = NULL; if (trie->root == NULL) trie->root = current; else parent->child = current; parent = current; goto clean; } tmp = parent == NULL ? trie->root : parent->child; previous = NULL; while (tmp != NULL && tmp->key != *key) { previous = tmp; tmp = tmp->next; } parent = tmp; if (previous == NULL || parent != NULL) goto clean; current = b_malloc(sizeof(b_trie_node_t)); current->key = *key; current->data = NULL; current->next = NULL; current->child = NULL; previous->next = current; parent = current; clean: if (*key == '\0') { if (parent->data != NULL && trie->free_func != NULL) trie->free_func(parent->data); parent->data = data; break; } key++; } }
static void test_bmalloc_diff() { b_malloc_init(128); void *a = b_malloc(4); void *b = b_malloc(4); assert((b - a) == BITMAP_BIT_NUM_BYTES); }
static void test_bmalloc_heap_full() { b_malloc_init(128); void *a = b_malloc(64); void *b = b_malloc(64); void *c = b_malloc(1); assert(c == NULL); }
/** allocate a new buddy structure * @param num_of_fragments number of fragments of the memory to be managed * @return pointer to the allocated buddy structure */ struct buddy *buddy_new(unsigned num_of_fragments) { struct buddy *self = NULL; size_t node_size; int i; if (num_of_fragments < 1 || !is_power_of_2(num_of_fragments)) { return NULL; } /* alloacte an array to represent a complete binary tree */ self = (struct buddy *) b_malloc(sizeof(struct buddy) + 2 * num_of_fragments * sizeof(size_t)); self->size = num_of_fragments; node_size = num_of_fragments * 2; /* initialize *longest* array for buddy structure */ int iter_end = num_of_fragments * 2 - 1; for (i = 0; i < iter_end; i++) { if (is_power_of_2(i+1)) { node_size >>= 1; } self->longest[i] = node_size; }
b_trie_t* b_trie_new(b_free_func_t free_func) { b_trie_t *trie = b_malloc(sizeof(b_trie_t)); trie->root = NULL; trie->free_func = free_func; return trie; }
static void test_bmalloc_basic_free() { b_malloc_init(128); void *a = b_malloc(4); void *a_old = a; void *b = b_malloc(8); void *c = b_malloc(23); void *d; b_free(a); b_free(b); b_free(c); d = b_malloc(55); assert(d == a_old); }