Review covers only minor stuff.
getline()
Avoid a technical exploit when size == 0. Although this code passes sizes more than 0, the function is hackable with size == 0.
When sz == 0
, as type size_t
, sz-1
is a huge value. Simply + 1 on the left-hand side instead.
// while (i < sz-1 && el == false)
while (i + 1 < sz && el == false)
Advanced: getline()
When a rare reading error occurs, getchar()
returns EOF
. Standard functions like fgets()
return NULL
even if some characters were successfully read on error. This differs from getline()
functionality. Since getline()
uses a return of 0 to indicate end-of-file (and no data read), a parallel functionality to fgets()
would also return 0 when an input error occurs (even of data read).
Easy, yet pedantic, change suggested:
if (i < sz) {
// add if
if (c == EOF && !feof(stdin)) { // EOF due to error
i = 0;
}
s[i] = '\0';
}
Consider const
When the source data does not change, using const
can make for 1) more clarity in function usage 2) greater applicability as then const char *f; copy(..., f);
is possible. 3) potentially more efficient code.
// void copy(char to[], char from[]);
void copy(char to[], char const from[]);
Advanced: Consider restrict
restrict
, roughly, implies that the data referenced by pointer only changes due to the code's function without side effects. Should from/to
overlap, copy()
as presently coded, can dramatically fail. restrict
informs the caller that to/from
should not overlap and thus allows the compiler to perform additional optimizations based on that.
// void copy(char to[], char const from[]);
void copy(char * restrict to, char const * restrict from);
Inconsistent documentation/function
Code is described as "trim trailing tabs and blanks" yet then trims ' '
, '\t'
and '\n'
. Recommended consistent documentation and function.
Sentinels
When printing string test output, especially ones with white-space removal, use sentinels to help show problems.
// printf("%s", line);
printf("<%s>", line);