/* Terminality - a portable terminal handling library * Copyright (C) 1998-2002, Emil Mikulic. * This is LGPL - look at COPYING.LIB */ /* Project: Terminality * File: xmem.c * Authors: Michal Safranek, Emil Mikulic * Description: Safe memory functions */ #include #include #include "xmem.h" const char xmem_rcsid[] = "$Id: xmem.c,v 1.6 2002/07/26 01:39:40 darkmoon Exp $"; int xmem_want_debug = 0; static void xmem_debug(char *who, char *fmt, ...) { va_list ap; if(!xmem_want_debug) return; assert(fmt != NULL); assert(who != NULL); va_start(ap, fmt); fprintf(xmem_debug_fd, "%s:", who); vfprintf(xmem_debug_fd, fmt, ap); fprintf(xmem_debug_fd, "\n"); fflush(xmem_debug_fd); va_end(ap); } static void xmem_error(char *who, char *what) { fprintf(stderr,"%s: %s\n", who, what); abort(); } void *xmalloc(size_t bytes) { void *temp; if (bytes < 1) xmem_error("xmalloc", "Requested less than 1 byte"); temp = malloc(bytes); xmem_debug("xmalloc", "Allocating %d bytes ... %p", bytes, temp); if (!temp) xmem_error("xmalloc", "Out of memory!"); return temp; } void *xrealloc(void *ptr, size_t bytes) { void *temp; if (bytes < 1) xmem_error("xrealloc", "Requested less than 1 byte"); temp = ptr ? realloc(ptr, bytes) : xmalloc(bytes); xmem_debug("xrealloc", "Reallocating %p to %d bytes ... %p", ptr, bytes, temp); if (!temp) xmem_error("xrealloc", "Out of memory!"); return temp; } void xfree(void *ptr) { xmem_debug("xfree", "Freeing memory at %p ...", ptr); if (ptr) free(ptr); }