1/* 2 * memory wrappers 3 * 4 * Copyright (c) Artem Bityutskiy, 2007, 2008 5 * Copyright 2001, 2002 Red Hat, Inc. 6 * 2001 David A. Schleef <ds@lineo.com> 7 * 2002 Axis Communications AB 8 * 2001, 2002 Erik Andersen <andersen@codepoet.org> 9 * 2004 University of Szeged, Hungary 10 * 2006 KaiGai Kohei <kaigai@ak.jp.nec.com> 11 * 12 * This program is free software; you can redistribute it and/or modify 13 * it under the terms of the GNU General Public License as published by 14 * the Free Software Foundation; either version 2 of the License, or 15 * (at your option) any later version. 16 * 17 * This program is distributed in the hope that it will be useful, 18 * but WITHOUT ANY WARRANTY; without even the implied warranty of 19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See 20 * the GNU General Public License for more details. 21 * 22 * You should have received a copy of the GNU General Public License 23 * along with this program; if not, write to the Free Software 24 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 25 */ 26 27#ifndef __MTD_UTILS_XALLOC_H__ 28#define __MTD_UTILS_XALLOC_H__ 29 30#include <stdlib.h> 31#include <string.h> 32 33/* 34 * Mark these functions as unused so that gcc does not emit warnings 35 * when people include this header but don't use every function. 36 */ 37 38__attribute__((unused)) 39static void *xmalloc(size_t size) 40{ 41 void *ptr = malloc(size); 42 43 if (ptr == NULL && size != 0) 44 sys_errmsg_die("out of memory"); 45 return ptr; 46} 47 48__attribute__((unused)) 49static void *xcalloc(size_t nmemb, size_t size) 50{ 51 void *ptr = calloc(nmemb, size); 52 53 if (ptr == NULL && nmemb != 0 && size != 0) 54 sys_errmsg_die("out of memory"); 55 return ptr; 56} 57 58__attribute__((unused)) 59static void *xzalloc(size_t size) 60{ 61 return xcalloc(1, size); 62} 63 64__attribute__((unused)) 65static void *xrealloc(void *ptr, size_t size) 66{ 67 ptr = realloc(ptr, size); 68 if (ptr == NULL && size != 0) 69 sys_errmsg_die("out of memory"); 70 return ptr; 71} 72 73__attribute__((unused)) 74static char *xstrdup(const char *s) 75{ 76 char *t; 77 78 if (s == NULL) 79 return NULL; 80 t = strdup(s); 81 if (t == NULL) 82 sys_errmsg_die("out of memory"); 83 return t; 84} 85 86#ifdef _GNU_SOURCE 87#include <stdarg.h> 88 89__attribute__((unused)) 90static int xasprintf(char **strp, const char *fmt, ...) 91{ 92 int cnt; 93 va_list ap; 94 95 va_start(ap, fmt); 96 cnt = vasprintf(strp, fmt, ap); 97 va_end(ap); 98 99 if (cnt == -1) 100 sys_errmsg_die("out of memory"); 101 102 return cnt; 103} 104#endif 105 106#endif /* !__MTD_UTILS_XALLOC_H__ */ 107