In KR C Programming Language there is a storage allocator described but how do I use it? How can I improve it? what algotihms are there available? Is this a trivial version of malloc that is shown?
#define ALLOCSIZE 10000
static char allocbuf[ALLOCSIZE];
static char *allocp = allocbuf; /* next free position */
char *alloc(int n) /* return pointer to n characters */
{
if (allocbuf + ALLOCSIZE - allocp >= n) { /* it fits */
allocp += n;
return allocp -n; /* old p */
} else
return 0;
}
void afree(char *p) {
if (p >= allocbuf && p < allocbuf + ALLOCSIZE)
allocp = p;
}
int main() {}
The real version of malloc() and free() are relatively easy to use. The places that you can get into trouble in its use are:
The version of a dynamic memory allocater that you've offered has issues. The most serious of which is that the afree() function doesn't know how much space was allocated during the alloc() and the only way that such a simple allocation scheme could work is if the memory was freed in a FIFO fashion. What you've implemented is a stack.
To make something useful you need to: