This code is from K&R C Programming page 109.
getline function is already limited by MAXLEN.
So it is obvious line returned by getline has limited size.
But the program puts line in the static storage allocator 'alloc' and fills it up with each lines until 10000 buffer is full.
But then, main() also has MAXLINES that readlines can return defined as 5000 (in the book). So I don't understand the purpose of using alloc function here.
It seems like readlines will work just fine without using alloc and strcpy line into p. It could be just likneptr[nlines++]=line;
What is the purpose of using alloc?
int readlines(char *lineptr[], int MAXLINE)
{
int len, nlines;
char line[MAXLEN];
char *p;
nlines = 0;
while((len=getline(line,MAXLEN))>0)
if ((nlines > MAXLINE)||(p=alloc(len))==NULL)
return -1;
else {
line[len - 1] = '\0';
strcpy(p, line);
lineptr[nlines++] = p;
}
return nlines;
}
#define ALLOCSIZE 10000
static char allocbuf[ALLOCSIZE];
static char *allocp = allocbuf;
char *alloc(int n)
{
if (allocbuf + ALLOCSIZE - allocp >= n) {
allocp += n;
return allocp - n;
}
else return 0;
}