#include #define ALLOCSIZE 10000 static char allocbuf[ALLOCSIZE]; static char *allocp = allocbuf; // This allocation function is taken from Chapter 5, p.101 of K & R. // It returns a character pointer to a chunk of 'n' contiguous bytes from // the statically-allocated buffer above. char *alloc(int n) { if ((allocbuf + ALLOCSIZE - allocp) >= n) { allocp += n; return allocp - n; } else return NULL; } // The matching afree() function from p.102 of K & R. // Note that this allocation scheme requires that we free memory chunks in // the reverse order of allocation, otherwise whackiness ensues. // How could we modify our alloc() and afree() functions to allow memory // chunks to be freed in arbitrary order? void afree(char *p) { if ((p >= allocbuf) && (p < allocbuf + ALLOCSIZE)) allocp = p; } int main() { char *h = "Hello World!"; char *s, *t; int *ip; int i = 0; // Request 13 bytes from our allocator. s = alloc(13); t = h; // Copy over string into new space. while (*s++ = *t++) ; // Request a block of 4 bytes, and cast it to an int pointer. (?!?!) ip = (int *)alloc(4); // This line of code works fine on an Intel machine, but causes a // "bus error" when run on a Sparc processor. This is because our // integer pointer is not properly word-aligned on the Sparc. // How could we modify our allocator to always give word-aligned pointers? *ip = 0x11223344; // Display the contents of the statically-allocated buffer, showing // where everything ended up after all of this dynamic allocation and // pointer business. for (i = 0, s = allocbuf; i < 24; i++, s++) printf("%3c\t0x%02X\n", *s, *s); }