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- */
19 * Allow debugging messages to track memory usage.
22 static long virt_make = 0;
23 static long virt_kill = 0;
24 static long virt_size = 0;
29 * Optional auxiliary "rnfree" function
31 vptr (*rnfree_aux)(vptr, huge) = NULL;
34 * Free some memory (allocated by ralloc), return NULL
36 vptr rnfree(vptr p, huge len)
38 /* Easy to free zero bytes */
39 if (len == 0) return (NULL);
43 /* Decrease memory count */
50 sprintf(buf, "Kill (%ld): %ld - %ld = %ld.",
51 len, virt_make, virt_kill, virt_make - virt_kill);
57 /* Use the "aux" function */
58 if (rnfree_aux) return ((*rnfree_aux)(p, len));
69 * Optional auxiliary "rpanic" function
71 vptr (*rpanic_aux)(huge) = NULL;
74 * The system is out of memory, so panic. If "rpanic_aux" is set,
75 * it can be used to free up some memory and do a new "ralloc()",
76 * or if not, it can be used to save things, clean up, and exit.
77 * By default, this function simply crashes the computer.
81 /* Hopefully, we have a real "panic" function */
82 if (rpanic_aux) return ((*rpanic_aux)(len));
84 /* Attempt to crash before icky things happen */
85 core("Out of Memory!");
88 return ((vptr)(NULL));
93 * Optional auxiliary "ralloc" function
95 vptr (*ralloc_aux)(huge) = NULL;
99 * Allocate some memory
101 vptr ralloc(huge len)
105 /* Allow allocation of "zero bytes" */
106 if (len == 0) return ((vptr)(NULL));
108 #ifdef VERBOSE_RALLOC
110 /* Count allocated memory */
113 /* Log important allocations */
117 sprintf(buf, "Make (%ld): %ld - %ld = %ld.",
118 len, virt_make, virt_kill, virt_make - virt_kill);
124 /* Use the aux function if set */
125 if (ralloc_aux) mem = (*ralloc_aux)(len);
127 /* Use malloc() to allocate some memory */
128 else mem = ((vptr)(malloc((size_t)(len))));
130 /* We were able to acquire memory */
131 if (!mem) mem = rpanic(len);
133 /* Return the memory, if any */
141 * Allocate a constant string, containing the same thing as 'str'
143 cptr string_make(cptr str)
149 /* Simple sillyness */
150 if (!str) return (str);
152 /* Get the number of chars in the string, including terminator */
153 while (str[len++]) /* loop */;
155 /* Allocate space for the string */
156 s = res = (char*)(ralloc(len));
158 /* Copy the string (with terminator) */
159 while ((*s++ = *t++) != 0) /* loop */;
161 /* Return the allocated, initialized, string */
167 * Un-allocate a string allocated above.
168 * Depends on no changes being made to the string.
170 errr string_free(cptr str)
174 /* Succeed on non-strings */
175 if (!str) return (0);
177 /* Count the number of chars in 'str' plus the terminator */
178 while (str[len++]) /* loop */;
180 /* Kill the buffer of chars we must have allocated above */
181 (void)rnfree((vptr)(str), len);