mem.c (1480B)
1 /* 2 * mem.c - memory allocation checkers 3 * Copyright (c) Clemens Ladisch <clemens@ladisch.de> 4 * 5 * This program is free software: you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation, either version 2 of the License, or 8 * (at your option) any later version. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 */ 18 19 #define _GNU_SOURCE 20 #include "aconfig.h" 21 #include <stdio.h> 22 #include <stdlib.h> 23 #include <stdarg.h> 24 #include <string.h> 25 #include <errno.h> 26 #include "die.h" 27 #include "mem.h" 28 29 static void check(void *p) 30 { 31 if (!p) 32 fatal_error("out of memory"); 33 } 34 35 void *ccalloc(size_t n, size_t size) 36 { 37 void *mem = calloc(n, size); 38 if (n && size) 39 check(mem); 40 return mem; 41 } 42 43 void *crealloc(void *ptr, size_t new_size) 44 { 45 ptr = realloc(ptr, new_size); 46 if (new_size) 47 check(ptr); 48 return ptr; 49 } 50 51 char *cstrdup(const char *s) 52 { 53 char *str = strdup(s); 54 check(str); 55 return str; 56 } 57 58 char *casprintf(const char *fmt, ...) 59 { 60 va_list ap; 61 char *str; 62 63 va_start(ap, fmt); 64 if (vasprintf(&str, fmt, ap) < 0) 65 check(NULL); 66 va_end(ap); 67 return str; 68 }