In my source code (in C), there is a line as below:
char line[1000] = "";
fgets(line, sizeof(line), file)
When I use parasoft to check, I receive two error:
In 'fgets' function call, do not pass long casted to int expression as '2' function argument
The type 'unsigned long' of function argument number '2' does not match declared type 'int'
I find nothing wrong with these lines in source code, so I don't know how to fix these error. Could you please give me a suggestion?
fgets
is accepting an int
for its second parameter. (IMHO, this is a defect)
sizeof
returns a value of type size_t
, which in your case seems to be an alias of unsigned Iong
. The issue with this is that an unsigned long
can be (much) too large to be convertible to an int
.
There's not much you can do about it here. To get rid of the error you might use a cast:
fgets(line, (int)sizeof(line), file);
Note that your use of sizeof
might get you into trouble if at some point you decide to change that array into a dynamically allocated one or if you refractor the code into different functions.