/* > c_alloc.c

 * SJ Middleton, 1993

 * Generic interface to the C library memory allocators.
 * Also contains a few variables and routines used by the rest of the memalloc functions.

 */

#include "werr.h"

#include <stdlib.h>

#include "memalloc.h"
#include "mem_int.h"

/* ------------------------------------------------------------------------------ */

static BOOL fatal_error = FALSE;

const char *memalloc__nextareaname = NULL;
int memalloc__nextmaxsize = -1;

BOOL memalloc__flexisdynamic = FALSE;

/* ------------------------------------------------------------------------------ */

/*
 * Called by all the allocators
 */

void alloc__checkerror(size_t size)
{
        if (fatal_error)
                werr(1, "Alloc failed for %d bytes\n", size);
}

/*
 * Used in command line programs to avoid checking each allocate
 */

void alloc_error(BOOL give)
{
        fatal_error = give;
}

/*
 * This has been added so that dynamic areas get named.
 * It is cleared after each allocate and itf not used then
 * wimpt_programname() is used instead
 */

void alloc_nextiscalled(const char *name)
{
        memalloc__nextareaname = name;
}

void alloc_nextmaxsize(int maxsize)
{
        memalloc__nextmaxsize = maxsize;
}

/* ------------------------------------------------------------------------------ */

BOOL c_alloc(void **anchor, size_t nbytes)
{
        void *p;

        alloc_nextiscalled(NULL);               /* clear name so it's not reused */
        alloc_nextmaxsize(-1);

        p = realloc(*anchor, nbytes);
        if (p || nbytes == 0)
        {
                *anchor = p;
                return TRUE;
        }
        alloc__checkerror(nbytes);
        return FALSE;
}

void c_free(void **anchor)
{
        void *p = *anchor;
        if (p)
        {
                free(p);
                *anchor = NULL;
        }
}

/* ------------------------------------------------------------------------------ */

/* eof c_alloc.c */
