1 /* $NetBSD: emalloc.c,v 1.1.1.1 2009/12/13 16:55:02 kardel Exp $ */ 2 3 /* 4 * emalloc - return new memory obtained from the system. Belch if none. 5 */ 6 #include "ntp_types.h" 7 #include "ntp_malloc.h" 8 #include "ntp_syslog.h" 9 #include "ntp_stdlib.h" 10 11 extern char *progname; 12 13 #if !defined(_MSC_VER) || !defined(_DEBUG) 14 15 16 void * 17 erealloc( 18 void * prev, 19 size_t size 20 ) 21 { 22 void * mem; 23 24 mem = realloc(prev, size ? size : 1); 25 26 if (NULL == mem) { 27 msyslog(LOG_ERR, 28 "fatal out of memory (%u bytes)", (u_int)size); 29 fprintf(stderr, 30 "%s: fatal out of memory (%u bytes)", progname, 31 (u_int)size); 32 exit(1); 33 } 34 35 return mem; 36 } 37 38 39 void * 40 emalloc( 41 size_t size 42 ) 43 { 44 return erealloc(NULL, size); 45 } 46 47 48 char * 49 estrdup( 50 const char * str 51 ) 52 { 53 char * copy; 54 55 copy = strdup(str); 56 57 if (NULL == copy) { 58 msyslog(LOG_ERR, 59 "fatal out of memory duplicating %u bytes", 60 (u_int)strlen(str) + 1); 61 fprintf(stderr, 62 "%s: fatal out of memory duplicating %u bytes", 63 progname, (u_int)strlen(str) + 1); 64 exit(1); 65 } 66 67 return copy; 68 } 69 70 #else /* below is _MSC_VER && _DEBUG */ 71 72 /* 73 * When using the debug MS CRT allocator, each allocation stores the 74 * callsite __FILE__ and __LINE__, which is then displayed at process 75 * termination, to track down leaks. We don't want all of our 76 * allocations to show up as coming from emalloc.c, so we preserve the 77 * original callsite's source file and line using macros which pass 78 * __FILE__ and __LINE__ as parameters to these routines. 79 */ 80 81 void * 82 debug_erealloc( 83 void * prev, 84 size_t size, 85 const char * file, /* __FILE__ */ 86 int line /* __LINE__ */ 87 ) 88 { 89 void * mem; 90 91 mem = _realloc_dbg(prev, size ? size : 1, 92 _NORMAL_BLOCK, file, line); 93 94 if (NULL == mem) { 95 msyslog(LOG_ERR, 96 "fatal: out of memory in %s line %d size %u", 97 file, line, (u_int)size); 98 fprintf(stderr, 99 "%s: fatal: out of memory in %s line %d size %u", 100 progname, file, line, (u_int)size); 101 exit(1); 102 } 103 104 return mem; 105 } 106 107 char * 108 debug_estrdup( 109 const char * str, 110 const char * file, /* __FILE__ */ 111 int line /* __LINE__ */ 112 ) 113 { 114 char * copy; 115 size_t bytes; 116 117 bytes = strlen(str) + 1; 118 copy = debug_erealloc(NULL, bytes, file, line); 119 memcpy(copy, str, bytes); 120 121 return copy; 122 } 123 124 #endif /* _MSC_VER && _DEBUG */ 125