広告
TAILQを使ってリストを実現する。
詳細はMan page of QUEUE参照。
tail.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
#include <stdio.h> #include <stdlib.h> #include <sys/queue.h> typedef struct memEntry { TAILQ_ENTRY(memEntry) entry; int32_t size; void* ptr; } memEntry_t; typedef struct { TAILQ_HEAD(tq_head, memEntry) head; int entry_count; } mngMemPool_t; static mngMemPool_t mngMem; void* allocateMemory(size_t size); void printAllMemory(void); void freeAllMemory(void); int main(void) { TAILQ_INIT(&mngMem.head); for (int i = 0; i < 10; i++) { void* ptr = allocateMemory(i * sizeof(int)); } printAllMemory(); freeAllMemory(); return 0; } void* allocateMemory(size_t size) { memEntry_t* ent; ent = malloc(sizeof(memEntry_t)); if (NULL == ent) { printf("out-of-memory"); exit(EXIT_FAILURE); } ent->ptr = malloc(size); if (NULL == ent->ptr) { free(ent); printf("out-of-memory"); exit(EXIT_FAILURE); } ent->size = size; TAILQ_INSERT_TAIL(&mngMem.head, ent, entry); return ent->ptr; } void printAllMemory(void) { memEntry_t* np = NULL; for (np = mngMem.head.tqh_first; np != NULL; np = np->entry.tqe_next) { printf("size=%d\n", np->size); } } void freeAllMemory(void) { while (mngMem.head.tqh_first != NULL) { memEntry_t* np = mngMem.head.tqh_first; TAILQ_REMOVE(&mngMem.head, np, entry); free(np->ptr); free(np); } } |
実行結果
1 2 3 4 5 6 7 8 9 10 11 12 |
$ gcc -std=gnu99 tailq.c -o tailq $ ./tailq size=0 size=4 size=8 size=12 size=16 size=20 size=24 size=28 size=32 size=36 |
広告
広告