/* 
 * Wrappers for malloc() etc.
 * Copyright Richard Tobin 1995
 */

#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>

#include "alloc.h"

void die_if_null(void *p, char *format, ...)
{
    va_list ap;

    if(p)
	return;

    va_start(ap, format);

    vfprintf(stderr, format, ap);

    exit(1);
}

void *safe_malloc(size_t size)
{
    void *p;

    if(size == 0)
	size = 1;

    p = malloc(size);
    die_if_null(p, "Can't malloc %d bytes\n", size);

    return p;
}

void *safe_realloc(void *p, size_t size)
{
    if(!p)
	return safe_malloc(size); /* in case realloc() doesn't work for null */

    if(size == 0)
	size = 1;

    p = realloc(p, size);
    die_if_null(p, "Can't realloc %d bytes\n", size);
    
    return p;
}

void safe_free(void *p)
{
    if(!p)
	return;			/* in case free() doesn't work for null */

    free(p);
}

char *xstrdup(char *s)
{
    char *t;

    t = strdup(s);
    die_if_null(t, "Can't strdup %d bytes\n", strlen(s));

    return t;
}
