adding char array with macro

The book uses this example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#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;
}


The logic here I don't understand:

if (allocbuf + ALLOCSIZE - allocp >= n)

allocbuf is a char array allocated with 10000 positions. We add that to ALLOCSIZE macro which is 10000. Does that return a value of 20000? If so, it doesn't make sense to do this because all we had to do was this:

if (allocbuf - allocp >= n)

That takes length of allocbuf which is 10000 and subtracts allocp from it. So if allocp is 1000 we are left with 9000 available slots. And we can use that to check if we have enough to allocate n elements.
closed account (Dy7SLyTq)
no, its called pointer arithmetic. lets say i have this:
int i[]={0,1,2,3,4,5,6,7,8,9};//an array with 10 elements
if i then do this:
int x=*(i+7); x is set to the 7th element ie 7 (i think... im gonna be lazy and not count)
so this could have also been written as:
int x=i[7];//like the processor ;)
so whats its doing is seeing if allocbuf[ALLOCSIZE] - allocp >= n
For simplicity let's keep everything in decimal
Let's take your sample example;

if start address of allocbuf is 10000, and if we have already allocated 1000 bytes, allocp will be 11000 and we are requesting for another 1000 bytes

the condition if( allocbuf + ALLOCSIZE - allocp >= n ) becomes
10000 + 10000 - 11000 >= 1000
20000- 11000 >= 1000
9000 >= 1000
This evaluates to be true and correct.

If we make the condition as

if( allocbuf - allocp >= n) it becomes
10000 - 11000 >= 1000
-1000 >= 1000
This evaluates to be false and won't work.

The new allocated address is always greater than the base pointer allocbuf. In your suggestion the result will become negative and hence won't work.
Last edited on
closed account (Dy7SLyTq)
allocbuff + ALLOCSIZE doesnt become 10000 + 10000, unless there was a major update to the c language
DTSCode you are right. The whole section was about pointer arithmetic. allocbuff returns the first index of the array. ALLOCSIZE is used for pointer arithmetic returning the value at the last position. So what this is basically saying is what you wrote before: if allocbuf[ALLOCSIZE] - allocp >= n
In case of char, as in the given example allocbuff + ALLOCSIZE can become 10000+10000 right? It's the same pointer arithmetic only one byte per character?
Topic archived. No new replies allowed.