diff --git a/src/salloc.c b/src/salloc.c index 6ec0767..ddec4cb 100644 --- a/src/salloc.c +++ b/src/salloc.c @@ -21,16 +21,24 @@ struct Chunk { struct SAlloc { size_t chunksz; //data size of each chunk Chunk *first; //head of the chunk list - Chunk *current; + Chunk *current; }; -static Chunk * -add_chunk(SAlloc *p) +static inline Chunk * +alloc_chunk(size_t sz) { Chunk *newchunk; - newchunk = malloc(sizeof *newchunk + p->chunksz - (sizeof *newchunk - offsetof(Chunk, data.data))); - if (newchunk == NULL) + newchunk = malloc(sizeof *newchunk + sz - (sizeof *newchunk - offsetof(Chunk, data.data))); + return newchunk; +} + +static Chunk * +add_chunk(SAlloc *p, Chunk *c) +{ + Chunk *newchunk; + + if (c == NULL) return NULL; if (p->current != NULL) @@ -50,8 +58,10 @@ next_chunk(SAlloc *p) if (p->current->next) { newchunk = p->current->next; newchunk->firstfree = 0; - } else - newchunk = add_chunk(p); + } else { + Chunk *c = alloc_chunk(p->chunksz); + newchunk = add_chunk(p, c); + } if (newchunk) p->current = newchunk; @@ -63,19 +73,21 @@ SAlloc * uc_new_salloc(size_t chunksz) { SAlloc *p; - Chunk *first; - p = malloc(sizeof *p); - if (p == NULL) + Chunk *first; + first = alloc_chunk(sizeof *p + chunksz); + if (first == NULL) { return NULL; - + } + p = &first->data.data[0]; + first->firstfree = sizeof *p; p->chunksz = chunksz; p->current = NULL; - if ((first = add_chunk(p)) == NULL) { + if ((first = add_chunk(p, first)) == NULL) { free(p); return NULL; } - + p->first = p->current = first; return p; @@ -86,7 +98,9 @@ uc_reset_salloc(SAlloc *p) { Chunk *tmp; - for(tmp = p->first; tmp; tmp = tmp->next) + tmp = p->first; + tmp->firstfree = sizeof *p; + for(tmp = tmp->next; tmp; tmp = tmp->next) tmp->firstfree = 0; p->current = p->first; @@ -97,9 +111,9 @@ uc_s_alloc(SAlloc *p,size_t sz) { Chunk *chunk; void *newmem; - + chunk = p->current; - if (chunk->firstfree + sz > p->chunksz) { + if (chunk->firstfree + sz > p->chunksz) { if (sz > p->chunksz) return NULL; @@ -107,7 +121,7 @@ uc_s_alloc(SAlloc *p,size_t sz) if (chunk == NULL) return NULL; } - + newmem = &chunk->data.data[chunk->firstfree]; chunk->firstfree += sz; @@ -119,17 +133,17 @@ uc_s_allocz(SAlloc *p,size_t sz) { void *newmem = uc_s_alloc(p, sz); - if (newmem != NULL) + if (newmem != NULL) memset(newmem, 0, sz); return newmem; } -static void +static void free_chunks(Chunk *chunk) { Chunk *next; - + for (next = NULL; chunk != NULL; chunk = next) { next = chunk->next; free(chunk); @@ -140,7 +154,5 @@ void uc_free_salloc(SAlloc *p) { free_chunks(p->first); - free(p); - }