#define ALLOCSZE 1000
static char allocbuf[ALLOCSZE]; /* storage for alloc */
static char *allocp=allocbuf; /* next free position */
char *alloc(int n) /* return pointer to n characters */
{
if(allocbuf+ALLOCSZE-allocp>=n)
{
allocp +=n;
return allocp-n;
}
else
return 0;
}
Is size of allocbuf equal to size of char in the condition ( if(allocbuf+ALLOCSZE-allocp>=n))
sizeof(allocbuf) is equal to the size of the array which is 1000.
When allocbuf
is used in the expression allocbuf+ALLOCSZE-allocp>=n
it will decay to a char pointer, thus the pointer arithmetic will be correct.
When you run out of memory, your function will return 0.
I suggest that you change the return value to NULL and the type of function argument to size_t. And don't forget that the memory you get from your function alloc() can only be used for type char
.