LIB-return-neg
Synopsis
A variable assigned using a library function that can return -1 as an error value is subsequently used where the value must be non-negative.
Enabled by default
Yes
Severity/Certainty
Medium/Medium

Full description
A variable assigned using a library function which can return -1 as an error value is subsequently used as a subscript or a size, both of which require the value to be non-negative. This might cause a crash or unpredictable behavior. These functions are inspected: ftell(), clock(), time(), mktime(), fprintf(), printf(), sprintf(), vfprintf(), vprintf(), vsprintf(), mblen(), mbstowcs(), mbstowc(), wcstombs(), and wctomb().
Coding standards
- CERT FIO04-C
Detect and handle input and output errors
- CWE 252
Unchecked Return Value
- CWE 394
Unexpected Status Code or Return Value
Code examples
The following code example fails the check and will give a warning:
#include <time.h>
#include <stdlib.h>
void example(void) {
time_t time = clock();
int *block = malloc(time); // time is used in a
// situation requiring it to be non-
// negative, but clock() may return -1
}
The following code example passes the check and will not give a warning about this issue:
#include <time.h>
#include <stdlib.h>
void example(void) {
time_t time = clock();
if (time>0){
int *block = malloc(time); // OK - time is checked
}
}