lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Roberto Ierusalimschy wrote:
What may be worth is to return 'block' when size == oldsize. (Lua
sometimes does this kind of call.)

Good to know. So this should be it (there is no test for (oldsize != 0) before memcpy, but that should be guaranteed when (block != NULL) unless something is broken in the caller):

static void *
l_alloc (void *ud, void *block, size_t oldsize, size_t size)
{
    (void)ud;
    /* free */
    if (size == 0) {
        free(block);
        return NULL;
    }

    /* realloc, same size */
    if (size == oldsize) {
        return block;
    }

    /* allocate for alloc | realloc */
    void *newblock = malloc(size);
    if (newblock == NULL) {
        return NULL;
    }

    /* realloc, different size */
    if (block != NULL) {
        memcpy(newblock, block, (oldsize < size) ? oldsize : size);
        free(block);
    }
    return newblock;
}

In a later phase of development, I'll probably add counters to do some statistics on allocator usage, sizes, etc. with a real program.

  Enrico