コアダンプの数だけ強くなれるよ

見習いエンジニアの備忘log

TAILQでリスト管理

TAILQを使ってリストを実現する。
詳細はMan page of QUEUE参照。


tail.c

#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);
    }
}

実行結果

$ 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