You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
brwsh/xalloc.c

78 lines
1.2 KiB

#define _POSIX_C_SOURCE 200809l
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <err.h>
#include <errno.h>
#include <stdarg.h>
#include "xalloc.h"
#define GUESS 240U
void *xmalloc(size_t n)
{
void *p = malloc(n);
if (!p)
err(errno, NULL);
return p;
}
void *xcalloc(size_t n, size_t s)
{
if (!n || !s)
err(EXIT_FAILURE, "calloc: invalid argument");
void *p = calloc(n, s);
if (!p)
err(errno, NULL);
return p;
}
void *xrealloc(void *p, size_t n)
{
void *r = realloc(p, n);
if (!r && n)
err(errno, NULL);
return r;
}
char *xstrdup(const char *s)
{
char *r = strdup(s);
if (!r)
err(errno, NULL);
return r;
}
int xasprintf(char **s, const char *fmt, ...)
{
int ret;
va_list ap;
va_start(ap, fmt);
ret = xvasprintf(s, fmt, ap);
va_end(ap);
return ret;
}
int xvasprintf(char **s, const char *fmt, va_list ap)
{
va_list ap2;
char *a;
unsigned int l=GUESS;
if (!(a=malloc(GUESS))) return -1;
va_copy(ap2, ap);
l=vsnprintf(a, GUESS, fmt, ap2);
va_end(ap2);
if (l<GUESS) {
char *b = xrealloc(a, l+1U);
*s = b ? b : a;
return l;
}
free(a);
if (!(*s=xmalloc(l+1U))) return -1;
return vsnprintf(*s, l+1U, fmt, ap);
}