Comment

Comment by thechao

Just a note about your 'exported memory allocation' API:

    struct hamt_allocator {
        void *(*malloc)(const size_t size);
        void *(*realloc)(void *chunk, const size_t size);
        void (*free)(void *chunk);
    };
This whole thing could just be:

    struct hamt_allocator {
        void *cookie;
        void*  (*realloc) (struct hamt_allocator* h, void* chk, const size_t size);
    };
With the following constraints:

1. `realloc(H, nullptr, N)` -- allocated N bytes

2. `realloc(H, p, 0)` -- frees the pointer p

3. `realloc(H, p, N)` -- resizes the pointer p

And, the user has access to a 'context' (`cookie`) so they can use a (for instance) pool allocation scheme. Personally, I like a slightly different API:

    struct hamt_allocator {
        void *cookie;
        void*  (*realloc) (struct hamt_allocator* h, void* chk, const size_t oldsize, const size_t newsize);
    };
With the following constraints:

1. `realloc(H, nullptr, 0, N)` -- allocated N bytes

2. `realloc(H, p, N, 0)` -- frees the pointer p

3. `realloc(H, p, N, M)` -- resizes the pointer p

But I know a lot of people get confused and/or don't like having to pass (& thus keep) so much information to the allocator.

parent thechao 3 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton