The following program is supposed to read a particular text file and print its contents line by line. However, it results in an infinite loop. Why?
#define __STDC_WANT_LIB_EXT2__ 1
#include <stdio.h>
int main(void)
{
char *line = NULL;
size_t buf_len;
size_t line_len;
FILE *fp = fopen("README.txt", "r");
while (1) {
line_len = getline(&line, &buf_len, fp);
if (line_len < 0)
break;
printf("%s", line);
}
return 0;
}
I noticed that I could fix the problem by changing line_len < 0
to line_len == -1
, but I don't understand the reason why this fixes the problem. Isn't -1
less than 0
?
(C compiler: gcc 9.4.0 on Ubuntu 20.04).
CodePudding user response:
line_len
is of type size_t
which should link to an unsigned long, since it is a unsigned value, it will never drop below 0 and instead wrap around to the highest value possible.
This is probably because -1
does not have any kind of type annotation:
unsigned long test1 = 18446744073709551615;
long test2 = -1;
printf("%d\n", test1 == test2);
returns true
because the bit values are the same.
C will do some type conversion (for instance 10.0f == 10
), but if the value is inlined it cannot know what type you need it to be.