UNIXworkcode

1 /******************************************************************************* 2 * * 3 * nedit_malloc.c -- Nirvana Editor memory handling * 4 * * 5 * Copyright (C) 2015 Ivan Skytte Joergensen * 6 * * 7 * This is free software; you can redistribute it and/or modify it under the * 8 * terms of the GNU General Public License as published by the Free Software * 9 * Foundation; either version 2 of the License, or (at your option) any later * 10 * version. In addition, you may distribute version of this program linked to * 11 * Motif or Open Motif. See README for details. * 12 * * 13 * This software is distributed in the hope that it will be useful, but WITHOUT * 14 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * 15 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * 16 * for more details. * 17 * * 18 * You should have received a copy of the GNU General Public License along with * 19 * software; if not, write to the Free Software Foundation, Inc., 59 Temple * 20 * Place, Suite 330, Boston, MA 02111-1307 USA * 21 * * 22 * Nirvana Text Editor * 23 * April, 1997 * 24 * * 25 * Written by Mark Edel * 26 * * 27 *******************************************************************************/ 28 29 #include "nedit_malloc.h" 30 #include <stdlib.h> 31 #include <stdio.h> 32 #include <string.h> 33 34 /* The reason for these routines are that we have a single place to handle 35 * out-of-memory conditions. Also memory returned by Xt* is freed with NEditFree 36 * (investigation back to X11R4 reveals that XtMalloc ultimately called plain 37 * malloc(). Also, XtMalloc() and friends take a 'Cardinal' size which is 38 * always 32-bit preventing 4GB+ file support 39 */ 40 41 void *NEditMalloc(size_t size) 42 { 43 void *ptr = malloc(size); 44 if(!ptr) { 45 fprintf(stderr,"NEditMalloc(%lu) failed\n", (unsigned long)size); 46 exit(1); 47 } 48 return ptr; 49 } 50 51 52 void *NEditCalloc(size_t nmemb, size_t size) 53 { 54 void *ptr = NEditMalloc(nmemb*size); 55 memset(ptr,0,nmemb*size); 56 return ptr; 57 } 58 59 60 void *NEditRealloc(void *ptr, size_t new_size) 61 { 62 void *new_ptr = realloc(ptr,new_size); 63 if(!new_ptr && new_size) { 64 fprintf(stderr,"NEditRealloc(%lu) failed\n", (unsigned long)new_size); 65 exit(1); 66 } 67 return new_ptr; 68 } 69 70 71 void NEditFree(void *ptr) 72 { 73 free(ptr); 74 } 75 76 77 char *NEditStrdup(const char *str) 78 { 79 size_t len; 80 if(!str) 81 return NULL; 82 len = strlen(str); 83 char *new_str= (char*)malloc(len+1); 84 if(!new_str) { 85 fprintf(stderr,"NEditStrdup(%lu) failed\n", (unsigned long)len); 86 exit(1); 87 } 88 memcpy(new_str,str,len+1); 89 return new_str; 90 } 91 92 char *NEditStrndup(const char *str, size_t len) 93 { 94 char *newstr = malloc(len+1); 95 newstr[len] = 0; 96 memcpy(newstr, str, len); 97 return newstr; 98 } 99