4 * Copyright (c) 1997 Ben Harrison
6 * This software may be copied and distributed for educational, research,
7 * and not for profit purposes provided that this copyright and statement
8 * are included in all such copies.
11 /* Purpose: Memory management routines -BEN- */
17 * Allow debugging messages to track memory usage.
20 static long virt_make = 0;
21 static long virt_kill = 0;
22 static long virt_size = 0;
27 * Optional auxiliary "rnfree" function
29 vptr (*rnfree_aux)(vptr, huge) = NULL;
32 * Free some memory (allocated by ralloc), return NULL
34 vptr rnfree(vptr p, huge len)
36 /* Easy to free zero bytes */
37 if (len == 0) return (NULL);
41 /* Decrease memory count */
47 sprintf(buf, "Kill (%ld): %ld - %ld = %ld.",
48 len, virt_make, virt_kill, virt_make - virt_kill);
54 /* Use the "aux" function */
55 if (rnfree_aux) return ((*rnfree_aux)(p, len));
66 * Optional auxiliary "rpanic" function
68 vptr (*rpanic_aux)(huge) = NULL;
71 * The system is out of memory, so panic. If "rpanic_aux" is set,
72 * it can be used to free up some memory and do a new "ralloc()",
73 * or if not, it can be used to save things, clean up, and exit.
74 * By default, this function simply crashes the computer.
78 /* Hopefully, we have a real "panic" function */
79 if (rpanic_aux) return ((*rpanic_aux)(len));
81 /* Attempt to crash before icky things happen */
82 core("Out of Memory!");
85 return ((vptr)(NULL));
90 * Optional auxiliary "ralloc" function
92 vptr (*ralloc_aux)(huge) = NULL;
96 * Allocate some memory
102 /* Allow allocation of "zero bytes" */
103 if (len == 0) return ((vptr)(NULL));
105 #ifdef VERBOSE_RALLOC
107 /* Count allocated memory */
110 /* Log important allocations */
114 sprintf(buf, "Make (%ld): %ld - %ld = %ld.",
115 len, virt_make, virt_kill, virt_make - virt_kill);
121 /* Use the aux function if set */
122 if (ralloc_aux) mem = (*ralloc_aux)(len);
124 /* Use malloc() to allocate some memory */
125 else mem = ((vptr)(malloc((size_t)(len))));
127 /* We were able to acquire memory */
128 if (!mem) mem = rpanic(len);
130 /* Return the memory, if any */
138 * Allocate a constant string, containing the same thing as 'str'
140 cptr string_make(cptr str)
146 /* Simple sillyness */
147 if (!str) return (str);
149 /* Get the number of chars in the string, including terminator */
150 while (str[len++]) /* loop */;
152 /* Allocate space for the string */
153 s = res = (char*)(ralloc(len));
155 /* Copy the string (with terminator) */
156 while ((*s++ = *t++) != 0) /* loop */;
158 /* Return the allocated, initialized, string */
164 * Un-allocate a string allocated above.
165 * Depends on no changes being made to the string.
167 errr string_free(cptr str)
171 /* Succeed on non-strings */
172 if (!str) return (0);
174 /* Count the number of chars in 'str' plus the terminator */
175 while (str[len++]) /* loop */;
177 /* Kill the buffer of chars we must have allocated above */
178 (void)rnfree((vptr)(str), len);