Patrick Welche <prlw1@cam.ac.uk>
[netbsd-mini2440.git] / external / bsd / ntp / dist / libntp / emalloc.c
blobd43a3aa0abe386c13e5d9f90ba79ec974710c5e7
1 /* $NetBSD$ */
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"
11 extern char *progname;
13 #if !defined(_MSC_VER) || !defined(_DEBUG)
16 void *
17 erealloc(
18 void * prev,
19 size_t size
22 void * mem;
24 mem = realloc(prev, size ? size : 1);
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);
35 return mem;
39 void *
40 emalloc(
41 size_t size
44 return erealloc(NULL, size);
48 char *
49 estrdup(
50 const char * str
53 char * copy;
55 copy = strdup(str);
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);
67 return copy;
70 #else /* below is _MSC_VER && _DEBUG */
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.
81 void *
82 debug_erealloc(
83 void * prev,
84 size_t size,
85 const char * file, /* __FILE__ */
86 int line /* __LINE__ */
89 void * mem;
91 mem = _realloc_dbg(prev, size ? size : 1,
92 _NORMAL_BLOCK, file, line);
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);
104 return mem;
107 char *
108 debug_estrdup(
109 const char * str,
110 const char * file, /* __FILE__ */
111 int line /* __LINE__ */
114 char * copy;
115 size_t bytes;
117 bytes = strlen(str) + 1;
118 copy = debug_erealloc(NULL, bytes, file, line);
119 memcpy(copy, str, bytes);
121 return copy;
124 #endif /* _MSC_VER && _DEBUG */