Not sure if K & R is correct - pointer arithmetic | Release procedure

Quote:

The if (allocbuf + ALLOCSIZE - allocp> = n) {test checks if there is enough space to satisfy a request for n characters. If there is, then the new allocp value will be no more than one outside of the allocbuf.

Code to which it relates:

#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 this be behind the last position in allocbuf? Which, in my opinion, is allocbuf [9999]

Anything besides this, for example. allocbuf [10000] is incorrect and is a memory leak, right?


- afree , . , , " " ? .

+5
2

allocp , , allocbuf.

, : allocp allocbuffer[9999], . , alloc(1)

allocbuf + ALLOCSIZE - allocp >= n

true , , char, char. . allocbuf - allocp == ALLOCSIZE allocbuf. false, , , allocbuf.


afree: , malloc, undefined. , . afree - , . , , .

, malloc calloc, .

+5

: , afree() C library free(), . . , . , , , .

, free() . , .

+2

All Articles