Ignoring return value from a standard library function that may return an errorCXX-W2022
When using standard library function like I/O functions and memory allocation functions, it's crucial to check the return values of these functions for any indication of an error. Assuming that these functions will always succeed and neglecting to check their return values is a risky practice that can result in unexpected or undefined behavior when an error occurs. It's essential to have a proper error-handling policy in place and make sure that all errors are detected and handled accordingly.
Here is the set of such function fread
, fputc
, clock
, fseek
, getwc
,
memchr
, realloc
, scanf
, strtod
, vfprintf_s
, wcstoll
. This list is
not exhustive. The table
here
lists all functions and the return values on failure of those functions.
It is recommended to check for the return value and handle errors appropriately. Otherwise, to ignore the return value, cast the value to void
, like (void) fread(...)
.
Bad practice
#include <stdio.h>
size_t read_at(FILE *file, long offset, void *buf, size_t nbytes) {
fseek(file, offset, SEEK_SET);
return fread(buf, 1, nbytes, file);
}
Recommended
#include <stdio.h>
size_t read_at(FILE *file, long offset, void *buf, size_t nbytes) {
if (fseek(file, offset, SEEK_SET) != 0) {
/* Indicate error to caller */
return 0;
}
return fread(buf, 1, nbytes, file);
}
Note
The example here might not be related to the issue shown in the dashboard. But the idea is not checking the return value. Please refer to the official API documentation for the meaning of the return value and handle the error cases.