I am currently studying the well-known book for C - The C Programming Language, 2Ed. And when I trying the code in P.29, I think there is something wrong in the getline function:
int getline(char s[], int lim) {
int c, i;
for (i=0; i<lim-1 && (c=getchar()) != EOF && c!='\n'; i++)
s[i] = c;
if (c == '\n') {
s[i] = c;
i++;
}
s[i] = '\0';
return i;
}
What if when the for loop ended, i == lim-1
and c == '\n'
? In this case, I think the array would be out of boundary, since s[lim]
would be set to '\0'.
Does anyone think this is wrong? Thanks for your help.
It is still relevant and still very useful with regards to learning the language. Learning the language doesn't require you to implement new practices or styles that assist in code readability, etc.
The &&
operator has "early-out" semantics. This means that if i == lim-1
, the rest of the condition is not executed - in particular, c = getchar()
will not be called.
This means that in this case, c
will have its value from the last iteration of the loop - and since the loop condition includes c != '\n'
, this value can't be '\n'
(or the loop would have exited last time around).
This is true as long as lim
is greater than 1, which must be a precondition of the function (because calling the function with lim
less than or equal to 1 would cause the uninitialised value of c
to be read).
So, let's look at some cases:
If lim == 0
:, then this will do undefined behavior. There's two places this will happen:
i == 0
and c == undefined
.c
at (c == '\n')
. It has no defined value yet, so it's undefined behavior.s
with: s[i] = '\0';
What if lim == 1
:
lim == 0
because c
has no value.What if lim == 2
, and the input string is "ab"
:
'a'
, and place it into s
.c
still being 'a'
.s == "a\0"
What if lim == 2
and the input string is "a\n"
(Which is the case you're worried about):
'a'
, and place it into s
.c
still being 'a'
.s == "a\0"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With