xmalloc.c

Go to the documentation of this file.
00001 /*
00002  * Copyright (C), 1998 by Eric S. Raymond.
00003  * Copyright (C), 2000-2002 by Contributors to the monit codebase. 
00004  *
00005  * This program is free software; you can redistribute it and/or
00006  * modify it under the terms of the GNU General Public License as
00007  * published by the Free Software Foundation; either version 2 of the
00008  * License, or (at your option) any later version.
00009  *
00010  * This program is distributed in the hope that it will be useful, but
00011  * WITHOUT ANY WARRANTY; without even the implied warranty of
00012  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013  * General Public License for more details.
00014  * 
00015  * You should have received a copy of the GNU General Public License
00016  * along with this program; if not, write to the Free Software Foundation,
00017  * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
00018  */
00019 
00020 #include <config.h>
00021 
00022 #include <string.h>
00023 #include <stdlib.h>
00024 #include <errno.h>
00025 
00026 #ifdef HAVE_STRING_H
00027 #include <string.h>
00028 #endif
00029 
00030 
00031 #include "monitor.h"
00032 
00033 
00049 /* ---------------------------------------------------------------- Public */
00050 
00051 
00052 void *xmalloc(int n) {
00053   
00054     void *p;
00055 
00056     p= (void *)malloc(n);
00057 
00058 /* Some malloc's don't return a valid pointer if you malloc(0), so check
00059    for that only if necessary. */
00060 
00061 #if ! HAVE_MALLOC
00062     if ( n == 0) {
00063 
00064       error("%s: passed a broken malloc 0\n", prog);
00065       exit(1);
00066 
00067     }
00068 #endif
00069 
00070     if ( p == NULL ) {
00071       
00072       error("%s: malloc failed -- %s\n", prog, STRERROR);
00073       exit(1);
00074       
00075     }
00076     
00077     return p;
00078 
00079 }
00080 
00081 void *xcalloc(long count, long nbytes) {
00082   
00083     void *p;
00084 
00085     p= (void *)calloc(count, nbytes);
00086     if ( p == NULL ) {
00087       
00088       error("%s: malloc failed -- %s\n", prog, STRERROR);
00089       exit(1);
00090       
00091     }
00092     
00093     return p;
00094 
00095 }
00096 
00097 
00098 char *xstrdup(const char *s) {
00099   
00100   char *p;
00101 
00102   ASSERT(s);
00103   
00104   p= (char *)xmalloc(strlen(s)+1);
00105   strcpy(p, s);
00106   
00107   return p;
00108   
00109 }
00110 
00111 
00112 void *xresize(void *p, long nbytes) {
00113 
00114   if (p == 0) {
00115     
00116     return xmalloc(nbytes);
00117 
00118   }
00119 
00120   p= realloc(p, nbytes);
00121   if(p == NULL) {
00122     
00123     error("%s: realloc failed -- %s\n", prog, STRERROR);
00124     exit(1);
00125     
00126   }
00127   
00128   return p;
00129   
00130 }
00131