I’m new to C and I’m reading “The C Programming Language” by K&R to learn it. I had a question about this example function appearing on pg 109 of the 2nd edition:
/* readlines: read input lines */
int readlines(char *lineptr[], int maxlines)
{
int len, nlines;
char *p, line[MAXLEN];
nlines = 0;
while ((len = getline(line, MAXLEN)) > 0)
if (nlines >= maxlines || p = alloc(len) == NULL)
return -1;
else {
line[len-1] = '\0'; /* delete newline */
strcpy(p, line);
lineptr[nlines++] = p;
}
return nlines;
}
I was wondering why *p is at all necessary here? p is allocated memory and then line is copied into it. Why can’t just line be used, so at the end lineptr[nlines++] = p could be replaced by lineptr[nlines++] = line.
If you don’t allocate memory for each line, you’ll end up with
lineptrbeing an array full of pointers to just the last line you read (not to mention to stack memory which is likely to be overwritten). Allocating memory for each line as you read makes the returned array make sense. As an example, let’s say thatlinehappens to get allocated on the stack at address 0x1000. If you make your suggested change, the resultinglineptrarray for an 8 line file would be:Yowch! Allocating memory for each line as you read it, and then copying the line into that allocated memory is the only solution.