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- */
13 #include "term/z-virt.h"
14 #include "term/z-util.h"
17 * Optional auxiliary "rnfree" function
19 vptr (*rnfree_aux)(vptr, huge) = NULL;
22 * Free some memory (allocated by ralloc), return NULL
24 vptr rnfree(vptr p, huge len)
26 /* Easy to free zero bytes */
27 if (len == 0) return (NULL);
29 /* Use the "aux" function */
30 if (rnfree_aux) return ((*rnfree_aux)(p, len));
40 * Optional auxiliary "rpanic" function
42 vptr (*rpanic_aux)(huge) = NULL;
45 * The system is out of memory, so panic. If "rpanic_aux" is set,
46 * it can be used to free up some memory and do a new "ralloc()",
47 * or if not, it can be used to save things, clean up, and exit.
48 * By default, this function simply crashes the computer.
52 /* Hopefully, we have a real "panic" function */
53 if (rpanic_aux) return ((*rpanic_aux)(len));
55 /* Attempt to crash before icky things happen */
56 core("Out of Memory!");
57 return ((vptr)(NULL));
62 * Optional auxiliary "ralloc" function
64 vptr (*ralloc_aux)(huge) = NULL;
68 * Allocate some memory
74 /* Allow allocation of "zero bytes" */
75 if (len == 0) return ((vptr)(NULL));
79 /* Count allocated memory */
82 /* Log important allocations */
86 sprintf(buf, "Make (%ld): %ld - %ld = %ld.",
87 len, virt_make, virt_kill, virt_make - virt_kill);
93 /* Use the aux function if set */
94 if (ralloc_aux) mem = (*ralloc_aux)(len);
96 /* Use malloc() to allocate some memory */
97 else mem = ((vptr)(malloc((size_t)(len))));
99 /* We were able to acquire memory */
100 if (!mem) mem = rpanic(len);
102 /* Return the memory, if any */
110 * Allocate a constant string, containing the same thing as 'str'
112 concptr string_make(concptr str)
118 /* Simple sillyness */
119 if (!str) return (str);
121 /* Get the number of chars in the string, including terminator */
122 while (str[len++]) /* loop */;
124 /* Allocate space for the string */
125 s = res = (char*)(ralloc(len));
127 /* Copy the string (with terminator) */
128 while ((*s++ = *t++) != 0) /* loop */;
130 /* Return the allocated, initialized, string */
136 * Un-allocate a string allocated above.
137 * Depends on no changes being made to the string.
139 errr string_free(concptr str)
143 /* Succeed on non-strings */
146 /* Count the number of chars in 'str' plus the terminator */
147 while (str[len++]) /* loop */;
149 /* Kill the buffer of chars we must have allocated above */
150 (void)rnfree((vptr)(str), len);