1 /* SCCS Id: @(#)alloc.c 3.4 1995/10/04 */
2 /* Copyright (c) Stichting Mathematisch Centrum, Amsterdam, 1985. */
3 /* NetHack may be freely redistributed. See license for details. */
5 /* to get the malloc() prototype from system.h */
6 #define ALLOC_C /* comment line for pre-compiled headers */
7 /* since this file is also used in auxiliary programs, don't include all the
8 * function declarations for all of nethack
10 #define EXTERN_H /* comment line for pre-compiled headers */
13 #if defined(MONITOR_HEAP) || defined(WIZARD)
14 char *FDECL(fmt_ptr, (const genericptr,char *));
20 extern void FDECL(free,(genericptr_t));
21 static void NDECL(heapmon_init);
23 static FILE *heaplog = 0;
24 static boolean tried_heaplog = FALSE;
27 long *FDECL(alloc,(unsigned int));
28 extern void VDECL(panic, (const char *,...)) PRINTF_F(1,2);
33 register unsigned int lth;
37 * a ridiculous definition, suppressing
38 * "possible pointer alignment problem" for (long *) malloc()
41 long dummy = ftell(stderr);
43 if(lth) dummy = 0; /* make sure arg is used */
46 register genericptr_t ptr;
50 if (!ptr) panic("Memory allocation failure; cannot get %u bytes", lth);
57 #if defined(MONITOR_HEAP) || defined(WIZARD)
59 # if defined(MICRO) || defined(WIN32)
60 /* we actually want to know which systems have an ANSI run-time library
61 * to know which support the new %p format for printing pointers.
62 * due to the presence of things like gcc, NHSTDC is not a good test.
63 * so we assume microcomputers have all converted to ANSI and bigger
64 * computers which may have older libraries give reasonable results with
67 # define MONITOR_PTR_FMT
70 # ifdef MONITOR_PTR_FMT
72 # define PTR_TYP genericptr_t
74 # define PTR_FMT "%06lx"
75 # define PTR_TYP unsigned long
78 /* format a pointer for display purposes; caller supplies the result buffer */
84 Sprintf(buf, PTR_FMT, (PTR_TYP)ptr);
92 /* If ${NH_HEAPLOG} is defined and we can create a file by that name,
93 then we'll log the allocation and release information to that file. */
97 char *logname = getenv("NH_HEAPLOG");
99 if (logname && *logname)
100 heaplog = fopen(logname, "w");
101 tried_heaplog = TRUE;
105 nhalloc(lth, file, line)
110 long *ptr = alloc(lth);
111 char ptr_address[20];
113 if (!tried_heaplog) heapmon_init();
115 (void) fprintf(heaplog, "+%5u %s %4d %s\n", lth,
116 fmt_ptr((genericptr_t)ptr, ptr_address),
118 /* potential panic in alloc() was deferred til here */
119 if (!ptr) panic("Cannot get %u bytes, line %d of %s",
126 nhfree(ptr, file, line)
131 char ptr_address[20];
133 if (!tried_heaplog) heapmon_init();
135 (void) fprintf(heaplog, "- %s %4d %s\n",
136 fmt_ptr((genericptr_t)ptr, ptr_address),
142 #endif /* MONITOR_HEAP */