int main() { Pool *p = Pool_create(); struct mystruct *s1 = Pool_malloc(p, &mystruct_alloc); struct mystruct *s2 = Pool_malloc(p, &mystruct_alloc); s1->name = malloc(10); s2->name = malloc(20); Pool_destroy(p); return 0; }
void *Pool_realloc(Pool *self, void *ptr, size_t newsize) #endif { size_t i; BlockHeader *p; BlockHeader *s; size_t new_alloc_block_size; if (self->init_flag != self) { DEBUGLOG(("Pool_realloc: pool is not initialized: %s(%d)\n", file, line)); assert(0); return 0; } if (!ptr) { #ifdef POOL_DEBUG return Pool_malloc_debug(self, newsize, file, line); #else return Pool_malloc(self, newsize); #endif } if (!newsize) { #ifdef POOL_DEBUG Pool_free_debug(self, ptr, file, line); #else Pool_free(self, ptr); #endif return 0; } #ifdef POOL_DEBUG p = (BlockHeader *) ((char *) ptr - (HEADER_SIZE + WALL_SIZE)); #else p = (BlockHeader *) ((char *) ptr - HEADER_SIZE); #endif if (p->magic != MAGIC_NO || !p->occupied) { DEBUGLOG(("Pool_realloc: NG pointer: %s(%d)\n", file, line)); assert(0); return 0; } #ifdef POOL_DEBUG new_alloc_block_size = ALIGN_UP(HEADER_SIZE + newsize + WALL_SIZE * 2); #else new_alloc_block_size = ALIGN_UP(HEADER_SIZE + newsize); #endif if (p->size >= new_alloc_block_size) { if (p->size >= 2 * new_alloc_block_size && new_alloc_block_size >= HEADER_SIZE + SPLIT_MIN) { /* 縮んだ分を空き領域として回収 */ s = (BlockHeader *) ((char *) p + new_alloc_block_size); s->occupied = 0; s->magic = MAGIC_NO; #ifndef POOL_SLIST s->prev = p; #endif if (p->next->occupied) { s->size = p->size - new_alloc_block_size; s->next = p->next; #ifndef POOL_SLIST p->next->prev = s; #endif } else { if (self->loop_p == p->next) { self->loop_p = p->next->next; } s->size = p->size - new_alloc_block_size + p->next->size; s->next = p->next->next; #ifndef POOL_SLIST p->next->next->prev = s; #endif } p->size = new_alloc_block_size; p->next = s; } #ifdef POOL_DEBUG p->alloc_size = newsize; for (i = 0; i < WALL_SIZE; i++) { ((char *) ptr)[newsize + i] = WALL_CHAR; } #endif return ptr; } /* 以下、拡張 */ if (p->next->occupied || p->size + p->next->size < new_alloc_block_size) { #ifdef POOL_DEBUG void *newptr = Pool_malloc_debug(self, newsize, file, line); #else void *newptr = Pool_malloc(self, newsize); #endif if (!newptr) { DEBUGLOG(("Pool_realloc: return NULL: %s(%d)\n", file, line)); return 0; } for (i = 0; #ifdef POOL_DEBUG i < p->alloc_size; #else i < p->size - HEADER_SIZE; #endif i++) { ((char *) newptr)[i] = ((char *) ptr)[i]; } #ifdef POOL_DEBUG Pool_free_debug(self, ptr, file, line); #else Pool_free(self, ptr); #endif return newptr; }