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