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!");
82 return ((vptr)(NULL));
87 * Optional auxiliary "ralloc" function
89 vptr (*ralloc_aux)(huge) = NULL;
93 * Allocate some memory
99 /* Allow allocation of "zero bytes" */
100 if (len == 0) return ((vptr)(NULL));
102 #ifdef VERBOSE_RALLOC
104 /* Count allocated memory */
107 /* Log important allocations */
111 sprintf(buf, "Make (%ld): %ld - %ld = %ld.",
112 len, virt_make, virt_kill, virt_make - virt_kill);
118 /* Use the aux function if set */
119 if (ralloc_aux) mem = (*ralloc_aux)(len);
121 /* Use malloc() to allocate some memory */
122 else mem = ((vptr)(malloc((size_t)(len))));
124 /* We were able to acquire memory */
125 if (!mem) mem = rpanic(len);
127 /* Return the memory, if any */
135 * Allocate a constant string, containing the same thing as 'str'
137 concptr string_make(concptr str)
143 /* Simple sillyness */
144 if (!str) return (str);
146 /* Get the number of chars in the string, including terminator */
147 while (str[len++]) /* loop */;
149 /* Allocate space for the string */
150 s = res = (char*)(ralloc(len));
152 /* Copy the string (with terminator) */
153 while ((*s++ = *t++) != 0) /* loop */;
155 /* Return the allocated, initialized, string */
161 * Un-allocate a string allocated above.
162 * Depends on no changes being made to the string.
164 errr string_free(concptr str)
168 /* Succeed on non-strings */
171 /* Count the number of chars in 'str' plus the terminator */
172 while (str[len++]) /* loop */;
174 /* Kill the buffer of chars we must have allocated above */
175 (void)rnfree((vptr)(str), len);