1 /* $Id: mandoc_aux.c,v 1.3 2014/07/09 08:20:34 schwarze Exp $ */ 2 /* 3 * Copyright (c) 2009, 2011 Kristaps Dzonsons <kristaps@bsd.lv> 4 * Copyright (c) 2014 Ingo Schwarze <schwarze@openbsd.org> 5 * 6 * Permission to use, copy, modify, and distribute this software for any 7 * purpose with or without fee is hereby granted, provided that the above 8 * copyright notice and this permission notice appear in all copies. 9 * 10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES 11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR 13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 17 */ 18 #ifdef HAVE_CONFIG_H 19 #include "config.h" 20 #endif 21 22 #include <sys/types.h> 23 24 #include <stdarg.h> 25 #include <stdlib.h> 26 #include <stdio.h> 27 #include <string.h> 28 29 #include "mandoc.h" 30 #include "mandoc_aux.h" 31 32 int 33 mandoc_asprintf(char **dest, const char *fmt, ...) 34 { 35 va_list ap; 36 int ret; 37 38 va_start(ap, fmt); 39 ret = vasprintf(dest, fmt, ap); 40 va_end(ap); 41 42 if (-1 == ret) { 43 perror(NULL); 44 exit((int)MANDOCLEVEL_SYSERR); 45 } 46 return(ret); 47 } 48 49 void * 50 mandoc_calloc(size_t num, size_t size) 51 { 52 void *ptr; 53 54 ptr = calloc(num, size); 55 if (NULL == ptr) { 56 perror(NULL); 57 exit((int)MANDOCLEVEL_SYSERR); 58 } 59 return(ptr); 60 } 61 62 void * 63 mandoc_malloc(size_t size) 64 { 65 void *ptr; 66 67 ptr = malloc(size); 68 if (NULL == ptr) { 69 perror(NULL); 70 exit((int)MANDOCLEVEL_SYSERR); 71 } 72 return(ptr); 73 } 74 75 void * 76 mandoc_realloc(void *ptr, size_t size) 77 { 78 79 ptr = realloc(ptr, size); 80 if (NULL == ptr) { 81 perror(NULL); 82 exit((int)MANDOCLEVEL_SYSERR); 83 } 84 return(ptr); 85 } 86 87 void * 88 mandoc_reallocarray(void *ptr, size_t num, size_t size) 89 { 90 91 ptr = reallocarray(ptr, num, size); 92 if (NULL == ptr) { 93 perror(NULL); 94 exit((int)MANDOCLEVEL_SYSERR); 95 } 96 return(ptr); 97 } 98 99 char * 100 mandoc_strdup(const char *ptr) 101 { 102 char *p; 103 104 p = strdup(ptr); 105 if (NULL == p) { 106 perror(NULL); 107 exit((int)MANDOCLEVEL_SYSERR); 108 } 109 return(p); 110 } 111 112 char * 113 mandoc_strndup(const char *ptr, size_t sz) 114 { 115 char *p; 116 117 p = mandoc_malloc(sz + 1); 118 memcpy(p, ptr, sz); 119 p[(int)sz] = '\0'; 120 return(p); 121 } 122