[BACK]Return to xmalloc.c CVS log [TXT][DIR] Up to [cvsweb.bsd.lv] / docbook2mdoc

File: [cvsweb.bsd.lv] / docbook2mdoc / xmalloc.c (download)

Revision 1.1, Sun Apr 28 15:03:29 2019 UTC (4 years, 11 months ago) by schwarze
Branch: MAIN
CVS Tags: VERSION_1_1_0, VERSION_1_0_2, HEAD

In this program, there is never a need to survive memory allocation
failure, and there are many places allocating memory.  Consequently,
the code can be simplified providing memory allocation functions
that error out on failure, in the conventional way.

/* $Id: xmalloc.c,v 1.1 2019/04/28 15:03:29 schwarze Exp $ */
/*
 * Copyright (c) 2019 Ingo Schwarze <schwarze@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include <sys/types.h>

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

#include "xmalloc.h"

/*
 * The implementation of the exiting allocator functions.
 */

void *
xcalloc(size_t nmemb, size_t size)
{
	void	*p;

	if ((p = calloc(nmemb, size)) == NULL) {
		perror(NULL);
		exit(6);
	}
	return p;
}

void *
xrealloc(void *p, size_t size)
{
	if ((p = realloc(p, size)) == NULL) {
		perror(NULL);
		exit(6);
	}
	return p;
}

void *
xreallocarray(void *p, size_t nmemb, size_t size)
{
	if ((p = reallocarray(p, nmemb, size)) == NULL) {
		perror(NULL);
		exit(6);
	}
	return p;
}

char *
xstrdup(const char *in)
{
	char	*out;

	if ((out = strdup(in)) == NULL) {
		perror(NULL);
		exit(6);
	}
	return out;
}

char *
xstrndup(const char *in, size_t maxlen)
{
	char	*out;

	if ((out = strndup(in, maxlen)) == NULL) {
		perror(NULL);
		exit(6);
	}
	return out;
}

int
xasprintf(char **dest, const char *fmt, ...)
{
	va_list	 ap;
	int	 ret;

	va_start(ap, fmt);
	ret = vasprintf(dest, fmt, ap);
	va_end(ap);

	if (ret == -1) {
		perror(NULL);
		exit(6);
	}
	return ret;
}