Search code examples
cmemorystorageallocation

C storage allocator usage?


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() {}

Solution

  • The real version of malloc() and free() are relatively easy to use. The places that you can get into trouble in its use are:

    • Freeing a location that you didn't allocate
    • Using an area of memory that you allocated by have already returned

    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:

    • Keep track of how much was allocated. For example put the byte count at the beginning of the allocated space and return a pointer that is after just after that counter. This allows afree() to know how much was allocated.
    • You need to have a free list so that memory can returned in any order. Typically you would have blocks of memory that you would manage and you round up to the block size when providing memory when requested.