Many All standard library functions including input/output functions and memory allocation functions return either a valid value or a value of the correct return type that indicates an error (for example, −1 or a null pointer). Assuming that all calls to such functions will succeed and failing to check the return value for an indication of an error is a dangerous practice that may lead to unexpected or undefined behavior when an error occurs. It is essential that programs detect and appropriately handle all errors in accordance with an error-handling policy, as discussed in ERR00-C. Adopt and implement a consistent and comprehensive error-handling policy.
Anchor | ||||
---|---|---|---|---|
|
Noncompliant Code Example (setlocale()
)
In this noncompliant example, the function utf8_to_ucs()
attempts to convert a sequence of UTF-8 characters to UCS. It first invokes setlocale()
to set the global locale to "en_US.UTF-8"
but does not check for failure. setlocale()
will fail by returning a null pointer, for example, when the locale is not installed. (The function may fail for other reasons, as well, such as the lack of resources.) Depending on the sequence of characters pointed to by utf8
, the subsequent call to mbstowcs()
may fail or result in the function storing an unexpected sequence of wide characters in the supplied buffer ucs
.
Code Block | ||||
---|---|---|---|---|
| ||||
size_t utf8_to_ucs(wchar_t *ucs, size_t n, const char *utf8) {
setlocale(LC_CTYPE, "en_US.UTF-8");
return mbstowcs(ucs, utf8, n);
}
|
...
The successful completion or failure of each of the standard library functions listed in the table below shall be determined either by comparing the function’s return value with the value listed in the column labeled “Error Return” or by calling one of the library functions mentioned in the footnotes to the same column.
Function | Successful Return | Error Return |
---|---|---|
aligned_alloc() | pointer to space | NULL |
asctime_s() | zero | nonzero |
at_quick_exit() | zero | nonzero |
atexit() | zero | nonzero |
bsearch() | pointer to matching element | NULL |
bsearch_s() | pointer to matching element | NULL |
btowc() | converted wide character | WEOF |
c16rtomb() | number of bytes | (size_t)(-1) |
c32rtomb() | number of bytes | (size_t)(-1) |
calloc() | pointer to space | NULL |
clock() | processor time | (clock_t)(-1) |
cnd_broadcast() | thrd_success | thrd_error |
cnd_init() | thrd_success | thrd_nomem or thrd_error |
cnd_signal() | thrd_success | thrd_error |
cnd_timedwait() | thrd_success | thrd_timedout or thrd_error |
cnd_wait() | thrd_success | thrd_error |
ctime_s() | zero | nonzero |
fclose() | zero | EOF (negative) |
fflush() | zero | EOF (negative) |
fgetc() | character read | EOF2 |
fgetpos() | zero | nonzero |
fgets() | pointer to string | NULL |
fgetwc() | wide character read | WEOF2 |
fopen() | pointer to stream | NULL |
fopen_s() | zero | nonzero |
fprintf() | number of characters (nonnegative) | negative |
fprintf_s() | number of characters (nonnegative) | negative |
fputc() | character written | EOF1 |
fputs() | nonnegative | EOF (negative) |
fputws() | nonnegative | EOF (negative) |
fread() | elements read | elements read |
freopen() | pointer to stream | NULL |
freopen_s() | zero | nonzero |
fscanf() | number of conversions (nonnegative) | EOF (negative) |
fscanf_s() | number of conversions (nonnegative) | EOF (negative) |
fseek() | zero | nonzero |
fsetpos() | zero | nonzero |
ftell() | file position | −1L |
fwprintf() | number of wide characters (nonnegative) | negative |
fwprintf_s() | number of wide characters (nonnegative) | negative |
fwrite() | elements written | elements written |
fwscanf() | number of conversions (nonnegative) | EOF (negative) |
fwscanf_s() | number of conversions (nonnegative) | EOF (negative) |
getc() | character read | EOF2 |
getchar() | character read | EOF2 |
getenv() | pointer to string | NULL |
getenv_s() | pointer to string | NULL |
gets_s() | pointer to string | NULL |
getwc() | wide character read | WEOF |
getwchar() | wide character read | WEOF |
gmtime() | pointer to broken-down time | NULL |
gmtime_s() | pointer to broken-down time | NULL |
localtime() | pointer to broken-down time | NULL |
localtime_s() | pointer to broken-down time | NULL |
malloc() | pointer to space | NULL |
mblen(), s != NULL | number of bytes | −1 |
mbrlen(), s != NULL | number of bytes or status | (size_t)(-1) |
mbrtoc16() | number of bytes or status | (size_t)(-1), errno == EILSEQ |
mbrtoc32() | number of bytes or status | (size_t)(-1), errno == EILSEQ |
mbrtowc(), s != NULL | number of bytes or status | (size_t)(-1), errno == EILSEQ |
mbsrtowcs() | number of non-null elements | (size_t)(-1), errno == EILSEQ |
mbsrtowcs_s() | zero | nonzero |
mbstowcs() | number of non-null elements | (size_t)(-1) |
mbstowcs_s() | zero | nonzero |
mbtowc(), s != NULL | number of bytes | −1 |
memchr() | pointer to located character | NULL |
mktime() | calendar time | (time_t)(-1) |
mtx_init() | thrd_success | thrd_error |
mtx_lock() | thrd_success | thrd_error |
mtx_timedlock() | thrd_success | thrd_timedout or thrd_error |
mtx_trylock() | thrd_success | thrd_busy or thrd_error |
mtx_unlock() | thrd_success | thrd_error |
printf_s() | number of characters (nonnegative) | negative |
putc() | character written | EOF1 |
putwc() | wide character written | WEOF |
raise() | zero | nonzero |
realloc() | pointer to space | NULL |
remove() | zero | nonzero |
rename() | zero | nonzero |
setlocale() | pointer to string | NULL |
setvbuf() | zero | nonzero |
scanf() | number of conversions (nonnegative) | EOF (negative) |
scanf_s() | number of conversions (nonnegative) | EOF (negative) |
signal() | pointer to previous function | SIG_ERR, errno > 0 |
snprintf() | number of characters that would be written (nonnegative) | negative |
snprintf_s() | number of characters that would be written (nonnegative) | negative |
sprintf() | number of non-null characters written | negative |
sprintf_s() | number of non-null characters written | negative |
sscanf() | number of conversions (nonnegative) | EOF (negative) |
sscanf_s() | number of conversions (nonnegative) | EOF (negative) |
strchr() | pointer to located character | NULL |
strerror_s() | zero | nonzero |
strftime() | number of non-null characters | zero |
strpbrk() | pointer to located character | NULL |
strrchr() | pointer to located character | NULL |
strstr() | pointer to located string | NULL |
strtod() | converted value | zero, errno == ERANGE |
strtof() | converted value | zero, errno == ERANGE |
strtoimax() | converted value | INTMAX_MAX or INTMAX_MIN, errno == ERANGE |
strtok() | pointer to first character of a token | NULL |
strtok_s() | pointer to first character of a token | NULL |
strtol() | converted value | LONG_MAX or LONG_MIN, errno == ERANGE |
strtold() | converted value | zero, errno == ERANGE |
strtoll() | converted value | LLONG_MAX or LLONG_MIN, errno == ERANGE |
strtoumax() | converted value | UINTMAX_MAX, errno == ERANGE |
strtoul() | converted value | ULONG_MAX, errno == ERANGE |
strtoull() | converted value | ULLONG_MAX, errno == ERANGE |
strxfrm() | length of transformed string | >= n |
swprintf() | number of non-null wide characters | negative |
swprintf_s() | number of non-null wide characters | negative |
swscanf() | number of conversions (nonnegative) | EOF (negative) |
swscanf_s() | number of conversions (nonnegative) | EOF (negative) |
thrd_create() | thrd_success | thrd_nomem or thrd_error |
thrd_detach() | thrd_success | thrd_error |
thrd_join() | thrd_success | thrd_error |
thrd_sleep() | zero | negative |
time() | calendar time | (time_t)(-1) |
timespec_get() | base | zero |
tmpfile() | pointer to stream | NULL |
tmpfile_s() | zero | nonzero |
tmpnam() | non-null pointer | NULL |
tmpnam_s() | zero | nonzero |
tss_create() | thrd_success | thrd_error |
tss_get() | value of thread-specific storage | zero |
tss_set() | thrd_success | thrd_error |
ungetc() | character pushed back | EOF (negative; see below) |
ungetwc() | character pushed back | WEOF (negative) |
vfprintf() | number of characters (nonnegative) | negative |
vfprintf_s() | number of characters (nonnegative) | negative |
vfscanf() | number of conversions (nonnegative) | EOF (negative) |
vfscanf_s() | number of conversions (nonnegative) | EOF (negative) |
vfwprintf() | number of wide characters (nonnegative) | negative |
vfwprintf_s() | number of wide characters (nonnegative) | negative |
vfwscanf() | number of conversions (nonnegative) | EOF (negative) |
vfwscanf_s() | number of conversions (nonnegative) | EOF (negative) |
vprintf_s() | number of characters (nonnegative) | negative |
vscanf() | number of conversions (nonnegative) | EOF (negative) |
vscanf_s() | number of conversions (nonnegative) | EOF (negative) |
vsnprintf() | number of characters that would be written (nonnegative) | negative |
vsnprintf_s() | number of characters that would be written (nonnegative) | negative |
vsprintf() | number of non-null characters (nonnegative) | negative |
vsprintf_s() | number of non-null characters (nonnegative) | negative |
vsscanf() | number of conversions (nonnegative) | EOF (negative) |
vsscanf_s() | number of conversions (nonnegative) | EOF (negative) |
vswprintf() | number of non-null wide characters | negative |
vswprintf_s() | number of non-null wide characters | negative |
vswscanf() | number of conversions (nonnegative) | EOF (negative) |
vswscanf_s() | number of conversions (nonnegative) | EOF (negative) |
vwprintf_s() | number of wide characters (nonnegative) | negative |
vwscanf() | number of conversions (nonnegative) | EOF (negative) |
vwscanf_s() | number of conversions (nonnegative) | EOF (negative) |
wcrtomb() | number of bytes stored | (size_t)(-1) |
wcschr() | pointer to located wide character | NULL |
wcsftime() | number of non-null wide characters | zero |
wcspbrk() | pointer to located wide character | NULL |
wcsrchr() | pointer to located wide character | NULL |
wcsrtombs() | number of non-null bytes | (size_t)(-1), errno == EILSEQ |
wcsrtombs_s() | zero | nonzero |
wcsstr() | pointer to located wide string | NULL |
wcstod() | converted value | zero, errno == ERANGE |
wcstof() | converted value | zero, errno == ERANGE |
wcstoimax() | converted value | INTMAX_MAX or INTMAX_MIN, errno == ERANGE |
wcstok() | pointer to first wide character of a token | NULL |
wcstok_s() | pointer to first wide character of a token | NULL |
wcstol() | converted value | LONG_MAX or LONG_MIN, errno == ERANGE |
wcstold() | converted value | zero, errno == ERANGE |
wcstoll() | converted value | LLONG_MAX or LLONG_MIN, errno == ERANGE |
wcstombs() | number of non-null bytes | (size_t)(-1) |
wcstombs_s() | zero | nonzero |
wcstoumax() | converted value | UINTMAX_MAX, errno == ERANGE |
wcstoul() | converted value | ULONG_MAX, errno == ERANGE |
wcstoull() | converted value | ULLONG_MAX, errno == ERANGE |
wcsxfrm() | length of transformed wide string | >= n |
wctob() | converted character | EOF |
wctomb(), s != NULL | number of bytes stored | −1 |
wctomb_s(), s != NULL | number of bytes stored | −1 |
wctrans() | valid argument to towctrans | zero |
wctype() | valid argument to iswctype | zero |
wmemchr() | pointer to located wide character | NULL |
wprintf_s() | number of wide characters (nonnegative) | negative |
wscanf() | number of conversions (nonnegative) | EOF (negative) |
wscanf_s() | number of conversions (nonnegative) | EOF (negative) |
When FIO35-C. Use feof() and ferror() to detect end-of-file and file errors when sizeof(int) == sizeof(char) applies, callers shall determine the success or failure of the functions above as follows:
by callingAnchor use_ferror use_ferror ferror
by callingAnchor use_feof_or_ferror use_feof_or_ferror ferror
andfeof
Anchor | ||||
---|---|---|---|---|
|
ungetc()
function does not set the error indicator even when it fails, so it is not possible to check for errors reliably unless it is known that the argument is not equal to EOF
. C99 states that "one character of pushback is guaranteed," so this should not be an issue if at most one character is ever pushed back before reading again. (See FIO13-C. Never push back anything other than one read character.)In addition to the C standard library functions above, POSIX defines the following functions designed specifically to dynamically allocate memory.
Function | Successful Return | Error Return |
|
---|---|---|---|
| pointer to a FILE object |
|
|
| pointer to a FILE object |
|
|
| 0 | non-zero #2 | unchanged #2 |
SettingAnchor 1 1 errno
is a POSIX [ISO/IEC 9945:2008] extension to the C standard.
On error,Anchor 2 2 posix_memalign()
returns a value that corresponds to one of the constants defined in the<errno.h>
header. The function does not seterrno
. Theposix_memalign()
function is optional and is not required to be provided by conforming implementations.
Anchor | ||||
---|---|---|---|---|
|
Noncompliant Code Example (setlocale()
)
In this noncompliant example, the function utf8_to_ucs()
attempts to convert a sequence of UTF-8 characters to UCS. It first invokes setlocale()
to set the global locale to "en_US.UTF-8"
but does not check for failure. setlocale()
will fail by returning a null pointer, for example, when the locale is not installed. (The function may fail for other reasons, as well, such as the lack of resources.) Depending on the sequence of characters pointed to by utf8
, the subsequent call to mbstowcs()
may fail or result in the function storing an unexpected sequence of wide characters in the supplied buffer ucs
.
Code Block | ||||
---|---|---|---|---|
| ||||
size_t utf8_to_ucs(wchar_t *ucs, size_t n, const char *utf8) {
setlocale(LC_CTYPE, "en_US.UTF-8");
return mbstowcs(ucs, utf8, n);
}
|
Anchor | ||||
---|---|---|---|---|
|
Compliant Solution (setlocale()
)
A compliant solution checks the value returned by setlocale()
and avoids calling mbstowcs()
if the function fails. The function also takes care to restore the locale to its initial setting before returning control to the caller.
Code Block | ||||
---|---|---|---|---|
| ||||
size_t utf8_to_ucs(wchar_t *ucs, size_t n, const char *utf8) {
const char *save;
save = setlocale(LC_CTYPE, "en_US.UTF-8");
if (NULL == save) {
/* Propagate error to caller */
return (size_t)-1;
}
n = mbstowcs(ucs, utf8, n);
if (NULL == setlocale(LC_CTYPE, save))
n = -1;
return n;
}
|
Anchor | ||||
---|---|---|---|---|
|
Noncompliant Code Example (signal()
)
In this noncompliant example, the function signal()
is invoked to install a handler for the SIGINT
signal. signal()
returns a pointer to the previously installed handler on success and the value SIG_ERR
on failure. However, because the caller fails to check for errors, when signal()
fails, the function may proceed with the lengthy computation without the ability to interrupt it.
Code Block | ||||
---|---|---|---|---|
| ||||
volatile sig_atomic_t interrupted;
void handle_interrupt(int signo) {
interrupted = 1;
}
int f() {
int result = 0;
signal(SIGINT, handle_interrupt);
while (0 == result && 0 == interrupted) {
/* Perform a lengthy computation */
}
/* Indicate success or failure */
return interrupted ? -1 : result;
}
|
Anchor | ||||
---|---|---|---|---|
|
Compliant Solution (signal()
)
A compliant solution checks the value returned by the signal()
function and avoids performing the lengthy computation when signal()
fails. The calling function also takes care to restore the disposition for the SIGINT
signal to its initial setting before returning control to the caller.
Code Block | ||||
---|---|---|---|---|
| ||||
volatile sig_atomic_t interrupted;
void handle_interrupt(int signo) {
interrupted = 1;
}
int f() {
int result = 0;
void (*saved_handler)(int);
saved_handler = signal(SIGINT, handle_interrupt);
if (SIG_ERR == saved_handler) {
/* Indicate failure */
return -1;
}
while (0 == result && 0 == interrupted) {
/* Perform a lengthy computation */
}
if (SIG_ERR == signal(SIGINT, saved_handler))
return -1;
/* Indicate success or failure */
return interrupted ? -1 : result;
}
|
Anchor | ||||
---|---|---|---|---|
|
Noncompliant Code Example (malloc()
)
In this noncompliant code example, temp_num
, tmp2
, and num_of_records
are under the control of a malicious user. The attacker can easily cause malloc()
to fail by providing a large value for num_of_records
.
Code Block | ||||
---|---|---|---|---|
| ||||
signal_info * start = malloc(num_of_records * sizeof(signal_info));
signal_info * point = (signal_info *)start;
point = start + temp_num - 1;
memcpy(point->sig_desc, tmp2, strlen(tmp2));
/* ... */ |
When malloc()
fails, it returns a null pointer that is assigned to start
. If start
is a null, an attacker can provide a value for temp_num
that, when scaled by the the sizeof signal_info
, references a writable address to which control is eventually transferred. The contents of the string referenced by tmp2
can then be used to overwrite the address, resulting in an arbitrary code execution vulnerability.
Compliant Solution (malloc()
)
To correct this error, ensure the pointer returned by malloc()
is not null. This also ensures compliance with MEM32-C. Detect and handle memory allocation errors.
Code Block | ||||
---|---|---|---|---|
| ||||
signal_info * start = malloc(num_of_records * sizeof(signal_info));
if (start == NULL) {
/* Handle Allocation Error */
}
signal_info * point = (signal_info *)start;
point = start + temp_num - 1;
memcpy(point->sig_desc, tmp2, strlen(tmp2));
/* ... */
|
Noncompliant Code Example (malloc()
)
In this noncompliant code example, input_string
is copied into dynamically allocated memory referenced by str
. However, the result of malloc()
is not checked before str
is referenced. Consequently, if malloc()
fails, the program has undefined behavior. (See undefined behavior 109 in Annex J of the C Standard.) In practice, an abnormal termination of the process typically occurs, providing an opportunity for a denial-of-service attack. In some cases, it may be the source of other vulnerabilities, as well. (See the ERR33-C. Detect and handle standard library 2errors section.) See also MEM32-C. Detect and handle memory allocation errors.
Code Block | ||||
---|---|---|---|---|
| ||||
void f(char *input_string) {
size_t size = strlen(input_string) + 1;
char *str = (char *)malloc(size);
strcpy(str, input_string);
/* ... */
}
|
Anchor | ||||
---|---|---|---|---|
|
Compliant Solution (malloc()
)
The malloc()
function, as well as the other memory allocation functions, returns either a null pointer or a pointer to the allocated space. Always test the returned pointer to ensure it is not NULL
before referencing the pointer. Handle the error condition appropriately when the returned pointer is NULL
. When recovery from the allocation failure is not possible, propagate the failure to the caller.
Code Block | ||||
---|---|---|---|---|
| ||||
int f(char *input_string) {
size_t size = strlen(input_string) + 1;
char *str = (char *)malloc(size);
if (str == NULL) {
/* Handle allocation failure and return error status */
return -1;
}
strcpy(str, input_string);
/* ... */
free(str);
return 0;
}
|
Noncompliant Code Example (realloc()
)
This noncompliant code example calls realloc()
to resize the memory referred to by p
. However, if realloc()
fails, it returns a null pointer. Consequently, the connection between the original block of memory and p
is severed, resulting in a memory leak.
Code Block | ||||
---|---|---|---|---|
| ||||
void *p;
size_t new_size = /* nonzero size */;
p = realloc(p, new_size);
if (p == NULL) {
/* Handle error */
}
|
When using realloc()
, it is important to account for zero-byte allocations. (See MEM04-C. Do not perform zero-length allocations.)
Anchor | ||||
---|---|---|---|---|
|
Compliant Solution (realloc()
)
In this compliant solution, the result of realloc()
is assigned to the temporary pointer q
and validated before it is assigned to the original pointer p
.
Code Block | ||||
---|---|---|---|---|
| ||||
void *p;
void *q;
size_t new_size= /* nonzero size */;
q = realloc(p, new_size);
if (q == NULL) {
/* Handle error */
}
else {
p = q;
}
|
Noncompliant Code Example (fseek
)
In this noncompliant code example, the fseek()
function is used to set the file position to a location offset
in the file referred to by file
prior to reading a sequence of bytes from the file. However, if an I/O error occurs during the seek operation the subsequent read will read will fill the buffer with the wrong contents.
Code Block | ||||
---|---|---|---|---|
| ||||
size_t read_at(FILE *file, long offset, void *buf, size_t nbytes) {
fseek(file, offset, SEEK_SET);
return fread(buf, 1, nbytes, file);
}
|
Compliant Solution (fseek
)
According to the C standard, the fseek()
function returns a non-zero value to indicate that an error occurred [ISO/IEC 9899:2011]. Testing for this condition before proceeding to read from the file eliminates the chance of operating on the wrong portion of the file if fseek()
failed. Always test the returned value to make sure an error did not occur before operating on the file. If an error does occur, handle it appropriately.
Code Block | ||||
---|---|---|---|---|
| ||||
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);
}
|
Noncompliant Code Example (snprintf
)
In the following noncompliant code example, snprinf()
is assumed to succeed. However, if the call fails (for example because of insufficient memory, as described in GNU libc bug 441945), the subsequent call to log_message()
is likely to result in undefined behavior since the character buffer is not initialized and need not be NUL terminated.
Code Block | ||||
---|---|---|---|---|
| ||||
extern void log_message(const char*);
void f(int i, int width, int prec) {
char buf[40];
snprintf(buf, sizeof buf, "i = %*.*i", width, prec, i);
log_message(buf);
/* ... */
}
|
Compliant Solution (snprintf
)
A compliant solution avoids assuming that snprintf()
succeeds regardless of its arguments and tests the return value of the function before using the buffer the function was passed to format output into. In addition, a compliant solution takes care to NUL-terminate the formatted string in case the provided buffer wasn't large enough for snprintf()
to append the terminating NUL.
Code Block | ||||
---|---|---|---|---|
| ||||
extern void log_message(const char*);
void f(int i, int width, int prec) {
char buf[40];
int n;
n = snprintf(buf, sizeof buf, "i = %*.*i", width, prec, i);
if (n < 0) {
/* Handle snprintf() error */
strcpy(buf, "unknown error");
}
/* NUL-terminate buffer in case of overflow */
buf[sizeof buf - 1] = '\0';
log_message(buf);
}
|
When the length of the formatted string is unbounded, it is best to invoke the function twice, once with a NULL
buffer to determine the size of output, then dynamically allocate a buffer of sufficient size, and finally call snprintf()
again to format the output into the dynamically allocated buffer. Even with this approach the success of all calls still needs to be tested, and any errors still need to be appropriately handled. A possible optimization is to first attempt to format the string into a reasonably small buffer allocated on the stack and only when the buffer turns out to be too small allocate one of a sufficient size dynamically. This approach is shown in the compliant solution below.
Code Block | ||||
---|---|---|---|---|
| ||||
void f(int i, int width, int prec) {
char buffer[20];
char *buf = buffer;
int n = sizeof buffer;
const char fmt[] = "i = %*.*i";
n = snprintf(buf, n, fmt, width, prec, i);
if (n < 0) {
/* Handle snprintf() error */
strcpy(buffer, "unknown error");
goto write_log;
}
if (n < sizeof buffer)
goto write_log;
buf = (char*)malloc(n + 1);
if (NULL == buf) {
/* Handle malloc() error */
strcpy(buffer, "unknown error");
goto write_log;
}
n = snprintf(buf, n, fmt, width, prec, i);
if (n < 0) {
/* Handle snprintf() error */
strcpy(buffer, "unknown error");
}
write_log:
log_message(buf);
if (buf != buffer)
free(buf);
}
|
Note that this solution correctly handles memory allocation errors in accordance with MEM32-C. Detect and handle memory allocation errors and uses the goto
statement as suggested in MEM12-C. Consider using a Goto-Chain when leaving a function on error when using and releasing resources.
Exceptions
EXP12-EX1: The exception from EXP12-C. Do not ignore values returned by functions still applies. If the return value is inconsequential or if any errors can be safely ignored, such as for functions called because of their side effects, the function should be explicitly cast to void
to signify programmer intent. For an example of this exception, see "Compliant Solution (Remove Existing Destination File)" under "Portable Behavior" in FIO10-C. Take care when using the rename() function.
ERR33-EX1: Ignore the return value of a function that cannot fail or whose return value cannot signify an error condition need not be diagnosed. For example, strcpy() is one such function.
Return values from the following functions do not need to be checked because their historical use has overwhelmingly omitted error checking, and the consequences are not relevant to security.
Function | Successful Return | Error Return |
---|---|---|
printf() | number of characters (nonnegative) | negative |
putchar() | character written | EOF |
puts() | nonnegative | EOF (negative) |
putwchar() | wide character written | WEOF |
vprintf() | number of characters (nonnegative) | negative |
vwprintf() | number of wide characters (nonnegative) | negative |
wprintf() | number of wide characters (nonnegative) | negative |
Risk Assessment
Failing to detect error conditions can lead to unpredictable results, including abnormal program termination and denial-of-service attacks or, in some situations, could even allow an attacker to run arbitrary code.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
ERR33-C | high | likely | medium | P18 | L1 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
| CHECKED_RETURN | Finds inconsistencies in how function call return values are handled. Coverity Prevent cannot discover all violations of this recommendation, so further verification is necessary. | |||||||
Compass/ROSE | Can detect violations of this recommendation when checking for violations of EXP12-C. Do not ignore values returned by functions and EXP34-C. Do not dereference null pointers.. | ||||||||
| 80 D | Partially implemented. | |||||||
PRQA QA-C |
| 3200 | Partially implemented | ||||||
Fortify SCA | V. 5.0 |
|
...
Compliant Solution (setlocale()
)
A compliant solution checks the value returned by setlocale()
and avoids calling mbstowcs()
if the function fails. The function also takes care to restore the locale to its initial setting before returning control to the caller.
Code Block | ||||
---|---|---|---|---|
| ||||
size_t utf8_to_ucs(wchar_t *ucs, size_t n, const char *utf8) {
const char *save;
save = setlocale(LC_CTYPE, "en_US.UTF-8");
if (NULL == save) {
/* Propagate error to caller */
return (size_t)-1;
}
n = mbstowcs(ucs, utf8, n);
if (NULL == setlocale(LC_CTYPE, save))
n = -1;
return n;
}
|
...
Noncompliant Code Example (signal()
)
In this noncompliant example, the function signal()
is invoked to install a handler for the SIGINT
signal. signal()
returns a pointer to the previously installed handler on success and the value SIG_ERR
on failure. However, because the caller fails to check for errors, when signal()
fails, the function may proceed with the lengthy computation without the ability to interrupt it.
Code Block | ||||
---|---|---|---|---|
| ||||
volatile sig_atomic_t interrupted;
void handle_interrupt(int signo) {
interrupted = 1;
}
int f() {
int result = 0;
signal(SIGINT, handle_interrupt);
while (0 == result && 0 == interrupted) {
/* Perform a lengthy computation */
}
/* Indicate success or failure */
return interrupted ? -1 : result;
}
|
...
Compliant Solution (signal()
)
A compliant solution checks the value returned by the signal()
function and avoids performing the lengthy computation when signal()
fails. The calling function also takes care to restore the disposition for the SIGINT
signal to its initial setting before returning control to the caller.
Code Block | ||||
---|---|---|---|---|
| ||||
volatile sig_atomic_t interrupted;
void handle_interrupt(int signo) {
interrupted = 1;
}
int f() {
int result = 0;
void (*saved_handler)(int);
saved_handler = signal(SIGINT, handle_interrupt);
if (SIG_ERR == saved_handler) {
/* Indicate failure */
return -1;
}
while (0 == result && 0 == interrupted) {
/* Perform a lengthy computation */
}
if (SIG_ERR == signal(SIGINT, saved_handler))
return -1;
/* Indicate success or failure */
return interrupted ? -1 : result;
}
|
...
Noncompliant Code Example (malloc()
)
In this noncompliant code example, temp_num
, tmp2
, and num_of_records
are under the control of a malicious user. The attacker can easily cause malloc()
to fail by providing a large value for num_of_records
.
Code Block | ||||
---|---|---|---|---|
| ||||
signal_info * start = malloc(num_of_records * sizeof(signal_info));
signal_info * point = (signal_info *)start;
point = start + temp_num - 1;
memcpy(point->sig_desc, tmp2, strlen(tmp2));
/* ... */ |
When malloc()
fails, it returns a null pointer that is assigned to start
. If start
is a null, an attacker can provide a value for temp_num
that, when scaled by the the sizeof signal_info
, references a writable address to which control is eventually transferred. The contents of the string referenced by tmp2
can then be used to overwrite the address, resulting in an arbitrary code execution vulnerability.
Compliant Solution (malloc()
)
To correct this error, ensure the pointer returned by malloc()
is not null. This also ensures compliance with MEM32-C. Detect and handle memory allocation errors.
Code Block | ||||
---|---|---|---|---|
| ||||
signal_info * start = malloc(num_of_records * sizeof(signal_info));
if (start == NULL) {
/* Handle Allocation Error */
}
signal_info * point = (signal_info *)start;
point = start + temp_num - 1;
memcpy(point->sig_desc, tmp2, strlen(tmp2));
/* ... */
|
Noncompliant Code Example (malloc()
)
In this noncompliant code example, input_string
is copied into dynamically allocated memory referenced by str
. However, the result of malloc()
is not checked before str
is referenced. Consequently, if malloc()
fails, the program has undefined behavior. (See undefined behavior 109 in Annex J of the C Standard.) In practice, an abnormal termination of the process typically occurs, providing an opportunity for a denial-of-service attack. In some cases, it may be the source of other vulnerabilities, as well. (See the ERR33-C. Detect and handle errors section.) See also MEM32-C. Detect and handle memory allocation errors.
Code Block | ||||
---|---|---|---|---|
| ||||
void f(char *input_string) {
size_t size = strlen(input_string) + 1;
char *str = (char *)malloc(size);
strcpy(str, input_string);
/* ... */
}
|
...
Compliant Solution (malloc()
)
The malloc()
function, as well as the other memory allocation functions, returns either a null pointer or a pointer to the allocated space. Always test the returned pointer to ensure it is not NULL
before referencing the pointer. Handle the error condition appropriately when the returned pointer is NULL
. When recovery from the allocation failure is not possible, propagate the failure to the caller.
Code Block | ||||
---|---|---|---|---|
| ||||
int f(char *input_string) {
size_t size = strlen(input_string) + 1;
char *str = (char *)malloc(size);
if (str == NULL) {
/* Handle allocation failure and return error status */
return -1;
}
strcpy(str, input_string);
/* ... */
free(str);
return 0;
}
|
Risk Assessment
Failing to detect error conditions can lead to unpredictable results, including abnormal program termination and denial-of-service attacks or, in some situations, could even allow an attacker to run arbitrary code.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
ERR33-C | high | likely | medium | P18 | L1 |
Related Coding Practices
Coding Practice | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
medium | unlikely | medium | P2 | L3 | |
low | probable | high | P2 | L3 | |
FLP32-C. Prevent or detect domain and range errors in math functions | medium | probable | medium | P8 | L2 |
high | likely | medium | P18 | L1 | |
medium | probable | high | P4 | L3 | |
FIO33-C. Detect and handle input output errors resulting in undefined behavior | high | probable | medium | P12 | L1 |
low | unlikely | medium | P2 | L3 | |
ERR00-C. Adopt and implement a consistent and comprehensive error-handling policy | medium | probable | high | P4 | L3 |
low | unlikely | high | P1 | L3 | |
medium | probable | high | P4 | L3 | |
API04-C. Provide a consistent and usable error-checking mechanism | medium | unlikely | medium | P2 | L3 |
low | likely | medium | P6 | L2 | |
low | likely | medium | P6 | L2 | |
medium | unlikely | medium | P2 | L3 | |
low | likely | medium | P6 | L2 | |
low | likely | medium | P6 | L2 |
Related Vulnerabilities
The vulnerability in Adobe Flash [VU#159523] arises because Flash neglects to check the return value from calloc()
. Even when calloc()
returns NULL
, Flash writes to an offset from the return value. Dereferencing NULL
usually results in a program crash, but dereferencing an offset from NULL
allows an exploit to succeed without crashing the program.
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Secure Coding Standard: ERR10-CPP. Check for error conditions
CERT C++ Secure Coding Standard: FIO04-CPP. Check for error conditionsDetect and handle input and output errors
MITRE CWE: CWE-252, "Unchecked return value"
MITRE CWE: CWE-253, "Incorrect check of function return value"
MITRE CWE: CWE-390, "Detection of error condition without action"
253, "Incorrect check of function return value"
MITRE CWE: CWE-390, "Detection of error condition without action"
MITRE CWE: CWE-391, "Unchecked error condition"
ISO/IEC 9899:2011 Sections 7.21.3, "Files," 7.21.4, "Operations on files," and 7.21.9, "File positioning functions"
ISO/IEC 9899:2011 Section 7.22.3, "Memory management functions"
ISO/IEC TR 17961 (Draft) Failing to detect and handle standard library errors [liberr]MITRE CWE: CWE-391, "Unchecked error condition"
Bibliography
[DHS 2006]. Handle All Errors Safely.
[Henricson 1997] Recommendation 12.1, Check for all errors reported from functions
...