Crotic Paradox Crotic Paradox - 3 years ago 190
C Question

Address arithmetic using a static buffer

#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 */
allocp +=n;
return allocp-n;
return 0;

Is size of allocbuf equal to size of char in the condition
( if(allocbuf+ALLOCSZE-allocp>=n))

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download