Unsure about correctness of a sentence from K&R - pointer arithmetic | Freeing procedure

Viewed 477

Quotation:

The test if (allocbuf + ALLOCSIZE - allocp >= n) { checks if there's enough room to satisfy a request for n characters. If there is, the new value of allocp would be at most one beyond the end of allocbuf.

The code which it relates to:

#define ALLOCSIZE 10000 /* size of available space */
static char allocbuf[ALLOCSIZE]; /* storage for alloc */
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
/* not enough room */
        return 0;
}
void afree(char *p) /* free storage pointed to by p */
{
    if (p >= allocbuf && p < allocbuf + ALLOCSIZE)
        allocp = p;
}

So how can it be beyond the last position in allocbuf? Which in my opinion is allocbuf[9999]

Anything beyond that eg. allocbuf[10000] is incorrect and is a memory leak, am I right?


The second part of the question - I though that afree function according to its name is deleting the value saved at particular places in an array. However as I can see it just moves the "recording head" just a few places to the left of an array? Data saved there remains untouched.

2 Answers
Related