irrelevant


"Safe" memory allocation utilities

I use a set of "safe" memory allocation utilities in my C projects. What I mean by "safe" is that they will abort on overflow and abort on allocation failure.

Overflow may happen if you mindlessly do something like:

void *mem = malloc(N * M);

And simply aborting on allocation failure means that I don't have to always check the returned pointer for NULL. If the system can't give me memory, I'm generally screwed anyway. YMMV on that point, depending on what you are building.

Anyway. Generally, I use variations of the following:

static inline void *mallocn(unsigned int n, size_t sz)
{
    if (would_overflow(n, sz)) {
        fprintf(stderr, "allocation of %d * %zu bytes would overflow\n", n, sz);

        abort();
    }

    return xmalloc(n * sz);
}

Where xmalloc is another helper:

static inline void *xmalloc(size_t sz)
{
    void *mem;

    if (!sz)
        return NULL;

    mem = malloc(sz);
    if (!mem)
        abort();

    return mem;
}

would_overflow is:

static inline bool would_overflow(unsigned int n, size_t sz)
{
    return n > SIZE_MAX / sz;
}