...
Many existing functions that return errno
are declared as returning a value of type int
. It is semantically unclear by looking at the function declaration or prototype if these functions return an error status or a value or, worse, some combination of the two. (See recommendation ERR02-C. Avoid in-band error indicators.)
...
Code Block | ||||
---|---|---|---|---|
| ||||
enum { NO_FILE_POS_VALUES = 3 };
int opener(
FILE *file,
int *width,
int *height,
int *data_offset
) {
int file_w;
int file_h;
int file_o;
fpos_t offset;
if (file == NULL) { return EINVAL; }
errno = 0;
if (fgetpos(file, &offset) != 0) { return errno; }
if (fscanf(file, "%i %i %i", &file_w, &file_h, &file_o)
!= NO_FILE_POS_VALUES) {
return EIO;
}
errno = 0;
if (fsetpos(file, &offset) != 0) { return errno; }
if (width != NULL) { *width = file_w; }
if (height != NULL) { *height = file_h; }
if (data_offset != NULL) { *data_offset = file_o; }
return 0;
}
|
This noncompliant code example , however, does comply with rule nevertheless complies with ERR30-C. Set errno to zero before calling a library function known to set errno, and check errno only after the function returns a value indicating failure.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <errno.h>
enum { NO_FILE_POS_VALUES = 3 };
errno_t opener(
FILE *file,
int *width,
int *height,
int *data_offset
) {
int file_w;
int file_h;
int file_o;
fpos_t offset;
if (file == NULL) { return EINVAL; }
errno = 0;
if (fgetpos(file, &offset) != 0 ) { return errno; }
if (fscanf(file, "%i %i %i", &file_w, &file_h, &file_o)
!= NO_FILE_POS_VALUES) {
return EIO;
}
errno = 0;
if (fsetpos(file, &offset) != 0 ) { return errno; }
if (width != NULL) { *width = file_w; }
if (height != NULL) { *height = file_h; }
if (data_offset != NULL) { *data_offset = file_o; }
return 0;
}
|
NOTE: EINVAL
and EIO
are not defined in C99the C standard, but they are available in most implementations and are defined in POSIX.
...
Failing to test for error conditions can lead to vulnerabilities of varying severity. Declaring functions that return an errno
with a return type of errno_t
will not eliminate this problem , but may reduce errors caused by programmers misunderstanding the purpose of a return value.
...
CERT C++ Secure Coding Standard: DCL09-CPP. Declare functions that return errno with a return type of errno_t
ISO/IEC 9899:19992011 Section 6.7.56.3, "Function declarators (including prototypes)"
...