0
votes

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;
}
1
The book teaches programming. It shows there how a rudimentary string allocation function could be written. Not everything makes sense by itself - Antti Haapala

1 Answers

1
votes

So I don't understand the purpose of using alloc function here.

If you're going to read more than one line, you're going to need more than one buffer to put those lines into. It makes sense to allocate buffers that are precisely the right size once the size is known rather than allocate a large number of large buffers.

It seems like readlines will work just fine without using alloc and strcpy line into p.

That can't work. Until we do something like p=alloc(len), p doesn't point to any buffer we can copy the line into. So how will we get the line there?

It could be just likneptr[nlines++]=line; What is the purpose of using alloc?

That would do no good. That would set every entry in likneptr[nlines++] to the same value, the address of line. Each line would overwrite the previous line. We need a new buffer for each line to go in that doesn't overwrite the buffer the previous line was held in. That requires more than one buffer.