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));
65 * Optional auxiliary "rpanic" function
67 vptr (*rpanic_aux)(huge) = NULL;
70 * The system is out of memory, so panic. If "rpanic_aux" is set,
71 * it can be used to free up some memory and do a new "ralloc()",
72 * or if not, it can be used to save things, clean up, and exit.
73 * By default, this function simply crashes the computer.
77 /* Hopefully, we have a real "panic" function */
78 if (rpanic_aux) return ((*rpanic_aux)(len));
80 /* Attempt to crash before icky things happen */
81 core("Out of Memory!");
84 return ((vptr)(NULL));
89 * Optional auxiliary "ralloc" function
91 vptr (*ralloc_aux)(huge) = NULL;
95 * Allocate some memory
101 /* Allow allocation of "zero bytes" */
102 if (len == 0) return ((vptr)(NULL));
104 #ifdef VERBOSE_RALLOC
106 /* Count allocated memory */
109 /* Log important allocations */
113 sprintf(buf, "Make (%ld): %ld - %ld = %ld.",
114 len, virt_make, virt_kill, virt_make - virt_kill);
120 /* Use the aux function if set */
121 if (ralloc_aux) mem = (*ralloc_aux)(len);
123 /* Use malloc() to allocate some memory */
124 else mem = ((vptr)(malloc((size_t)(len))));
126 /* We were able to acquire memory */
127 if (!mem) mem = rpanic(len);
129 /* Return the memory, if any */
137 * Allocate a constant string, containing the same thing as 'str'
139 concptr string_make(concptr str)
145 /* Simple sillyness */
146 if (!str) return (str);
148 /* Get the number of chars in the string, including terminator */
149 while (str[len++]) /* loop */;
151 /* Allocate space for the string */
152 s = res = (char*)(ralloc(len));
154 /* Copy the string (with terminator) */
155 while ((*s++ = *t++) != 0) /* loop */;
157 /* Return the allocated, initialized, string */
163 * Un-allocate a string allocated above.
164 * Depends on no changes being made to the string.
166 errr string_free(concptr str)
170 /* Succeed on non-strings */
171 if (!str) return (0);
173 /* Count the number of chars in 'str' plus the terminator */
174 while (str[len++]) /* loop */;
176 /* Kill the buffer of chars we must have allocated above */
177 (void)rnfree((vptr)(str), len);