language large_string | page_id int64 | page_url large_string | chapter int64 | section int64 | rule_id large_string | title large_string | intro large_string | noncompliant_code large_string | compliant_solution large_string | risk_assessment large_string | breadcrumb large_string |
|---|---|---|---|---|---|---|---|---|---|---|---|
c | 87,152,282 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152282 | 3 | 3 | EXP12-C | Do not ignore values returned by functions | Many functions return useful values whether or not the function has side effects. In most cases, this value is used to signify whether the function successfully completed its task or if some error occurred (see
). Other times, the value is the result of some computation and is an integral part of the function's API.
Su... | void func(char* name) {
char* s = NULL;
asprintf(&s,"Hello, %s!\n", name);
(void) puts(s);
free(s);
}
## Noncompliant Code Example
The
asprintf()
function has been provided by the GNU C library. It works like
sprintf()
, but if given a null pointer as the destination string, it will create a buffer sufficient ... | void func(char* name) {
char* s = NULL;
if (asprintf(&s,"Hello, %s!\n", name) < 0) {
/* Handle error */
}
(void) puts(s);
free(s);
}
## Compliant Solution
## This compliant solution checks to make sure no error occurred.
#ccccff
c
void func(char* name) {
char* s = NULL;
if (asprintf(&s,"Hello, %s!\n", n... | ## Risk Assessment
Failure to handle error codes or other values returned by functions can lead to incorrect program flow and violations of data integrity.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP12-C
Medium
Unlikely
Yes
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
er... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
c | 87,152,264 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152264 | 3 | 3 | EXP13-C | Treat relational and equality operators as if they were nonassociative | The relational and equality operators are left-associative in C. Consequently, C, unlike many other languages, allows chaining of relational and equality operators. Subclause 6.5.8, footnote 107, of the C Standard [
ISO/IEC 9899:2011
], says:
The expression
a<b<c
is not interpreted as in ordinary mathematics. As the sy... | int a = 2;
int b = 2;
int c = 2;
/* ... */
if (a < b < c) /* Misleading; likely bug */
/* ... */
if (a == b == c) /* Misleading; likely bug */
## Noncompliant Code Example
Although this noncompliant code example compiles correctly, it is unlikely that it means what the author of the code intended:
#FFcccc
c
int a = 2;... | if ( (a < b) && (b < c) ) /* Clearer and probably what was intended */
/* ... */
if ( (a == b) && (a == c) ) /* Ditto */
## Compliant Solution
Treat relational and equality operators as if it were invalid to chain them:
#ccccff
c
if ( (a < b) && (b < c) ) /* Clearer and probably what was intended */
/* ... */
if ( (a ... | ## Risk Assessment
Incorrect use of relational and equality operators can lead to incorrect control flow.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP13-C
Low
Unlikely
Yes
Yes
P3
L3
Automated Detection
Tool
Version
Checker
Description
chained-comparison
Fully checked
CC2.EXP13
Fully implemented
Opt... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
c | 87,152,251 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152251 | 3 | 3 | EXP14-C | Beware of integer promotion when performing bitwise operations on integer types smaller than int | Deprecated
This guideline has been deprecated by
Integer types smaller than
int
are promoted when an operation is performed on them. If all values of the original type can be represented as an
int
, the value of the smaller type is converted to an
int
; otherwise, it is converted to an
unsigned int
(see
). If the conve... | uint8_t port = 0x5a;
uint8_t result_8 = ( ~port ) >> 4;
## Noncompliant Code Example
This noncompliant code example demonstrates how performing bitwise operations on integer types smaller than
int
may have unexpected results.
#FFcccc
c
uint8_t port = 0x5a;
uint8_t result_8 = ( ~port ) >> 4;
In this example, a bitwise ... | uint8_t port = 0x5a;
uint8_t result_8 = (uint8_t) (~port) >> 4;
## Compliant Solution
In this compliant solution, the bitwise complement of
port
is converted back to 8 bits. Consequently,
result_8
is assigned the expected value of
0x0aU
.
#ccccff
c
uint8_t port = 0x5a;
uint8_t result_8 = (uint8_t) (~port) >> 4; | ## Risk Assessment
Bitwise operations on shorts and chars can produce incorrect data.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP14-C
low
likely
No
No
P3
L3
Automated Detection
Tool
Version
Checker
Description
Supported
CertC-EXP14
Fully implemented
LANG.CAST.RIP
Risky integer promotion
... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
c | 87,152,218 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152218 | 3 | 3 | EXP15-C | Do not place a semicolon on the same line as an if, for, or while statement | Do not use a semicolon on the same line as an
if
,
for
, or
while
statement because it typically indicates programmer error and can result in unexpected behavior. | if (a == b); {
/* ... */
}
## Noncompliant Code Example
## In this noncompliant code example, a semicolon is used on the same line as anifstatement:
#FFcccc
c
if (a == b); {
/* ... */
} | if (a == b) {
/* ... */
}
## Compliant Solution
It is likely, in this example, that the semicolon was accidentally inserted:
#ccccff
c
if (a == b) {
/* ... */
} | ## Risk Assessment
Errors of omission can result in unintended program flow.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP15-C
High
Likely
Yes
Yes
P27
L1
Automated Detection
Tool
Version
Checker
Description
empty-body
Fully checked
CertC-EXP15
Fully implemented
LANG.STRUCT.EBS
Empty branch... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
c | 87,152,223 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152223 | 3 | 3 | EXP16-C | Do not compare function pointers to constant values | Comparing a function pointer to a value that is not a null function pointer of the same type will be diagnosed because it typically indicates programmer error and can result in
unexpected behavior
. Implicit comparisons will be diagnosed, as well. | /* First the options that are allowed only for root */
if (getuid == 0 || geteuid != 0) {
/* ... */
}
/* First the options that are allowed only for root */
if (getuid() == 0 || geteuid != 0) {
/* ... */
}
int do_xyz(void);
int f(void) {
/* ... */
if (do_xyz) {
return -1; /* Indicate failure */
}
/* ... | /* First the options that are allowed only for root */
if (getuid() == 0 || geteuid() != 0) {
/* ... */
}
/* First the options that are allowed only for root */
if (getuid == (uid_t(*)(void))0 || geteuid != (uid_t(*)(void))0) {
/* ... */
}
int do_xyz(void);
int f(void) {
/* ... */
if (do_xyz()) {
r... | ## Risk Assessment
Errors of omission can result in unintended program flow.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP16-C
Low
Likely
Yes
No
P6
L2
Automated Detection
Tool
Version
Checker
Description
function-name-constant-comparison
Partially checked
BAD_COMPARE
Can detect the specifi... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
c | 87,152,259 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152259 | 3 | 3 | EXP19-C | Use braces for the body of an if, for, or while statement | Opening and closing braces for
if
,
for
, and
while
statements should always be used even if the statement's body contains only a single statement.
If an
if
,
while
, or
for
statement is used in a macro, the macro definition should not conclude with a semicolon. (See
.)
Braces improve the uniformity and readability of ... | int login;
if (invalid_login())
login = 0;
else
login = 1;
int login;
if (invalid_login())
login = 0;
else
printf("Login is valid\n"); /* Debugging line added here */
login = 1; /* This line always gets executed
/* regardless of a valid login! */
int privi... | int login;
if (invalid_login()) {
login = 0;
} else {
login = 1;
}
int privileges;
if (invalid_login()) {
if (allow_guests()) {
privileges = GUEST;
}
} else {
privileges = ADMINISTRATOR;
}
while (invalid_login()) {}
## Compliant Solution
## In the compliant solution, opening and closing braces are u... | ## Risk Assessment
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP19-C
Medium
Probable
Yes
Yes
P12
L1
Automated Detection
Tool
Version
Checker
Description
compound-ifelse
compound-loop
Fully checked
CertC-EXP19
Fully implemented
C2212
MISRA.IF.NO_COMPOUND
MISRA.STMT.NO_COMPOUND
LDRA tool sui... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
c | 87,152,324 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152324 | 3 | 3 | EXP20-C | Perform explicit tests to determine success, true and false, and equality | Perform explicit tests to determine success, true/false, and equality to improve the readability and maintainability of code and for compatibility with common conventions.
In particular, do not default the test for nonzero. For instance, suppose a
foo()
function returns 0 to indicate failure or a nonzero value to indic... | LinkedList bannedUsers;
int is_banned(User usr) {
int x = 0;
Node cur_node = (bannedUsers->head);
while (cur_node != NULL) {
if(!strcmp((char *)cur_node->data, usr->name)) {
x++;
}
cur_node = cur_node->next;
}
return x;
}
void processRequest(User usr) {
if(is_banned(usr) == 1) {
r... | LinkedList bannedUsers;
int is_banned(User usr) {
int x = 0;
Node cur_node = (bannedUsers->head);
while(cur_node != NULL) {
if (strcmp((char *)cur_node->data, usr->name)==0) {
x++;
}
cur_node = cur_node->next;
}
return x;
}
void processRequest(User usr) {
if (is_banned(usr) != 0) {
... | ## Risk Assessment
Code that does not conform to the common practices presented is difficult to maintain. Bugs can easily arise when modifying helper functions that evaluate true/false or success/failure. Bugs can also easily arise when modifying code that tests for equality using a comparison function that obeys the s... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP) |
c | 87,152,202 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152202 | 2 | 3 | EXP30-C | Do not depend on the order of evaluation for side effects | Evaluation of an expression may produce
side effects
. At specific points during execution, known as
sequence points
, all side effects of previous evaluations are complete, and no side effects of subsequent evaluations have yet taken place. Do not depend on the order of evaluation for side effects unless there is an i... | #include <stdio.h>
void func(int i, int *b) {
int a = i + b[++i];
printf("%d, %d", a, i);
}
extern void func(int i, int j);
void f(int i) {
func(i++, i);
}
extern void c(int i, int j);
int glob;
int a(void) {
return glob + 10;
}
int b(void) {
glob = 42;
return glob;
}
void func(void) {
c(a(), b(... | #include <stdio.h>
void func(int i, int *b) {
int a;
++i;
a = i + b[i];
printf("%d, %d", a, i);
}
#include <stdio.h>
void func(int i, int *b) {
int a = i + b[i + 1];
++i;
printf("%d, %d", a, i);
}
extern void func(int i, int j);
void f(int i) {
i++;
func(i, i);
}
extern void func(int i, int j);... | ## Risk Assessment
Attempting to modify an object multiple times between sequence points may cause that object to take on an unexpected value, which can lead to
unexpected program behavior
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP30-C
Medium
Probable
No
Yes
P8
L2
Automated Detection
Tool
Versi... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,152,412 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152412 | 2 | 3 | EXP32-C | Do not access a volatile object through a nonvolatile reference | An object that has volatile-qualified type may be modified in ways unknown to the
implementation
or have other unknown
side effects
. Referencing a volatile object by using a non-volatile lvalue is
undefined behavior
. The C Standard, 6.7.4 paragraph 7 [
ISO/IEC 9899:2024
], states
If an attempt is made to refer to an ... | #include <stdio.h>
void func(void) {
static volatile int **ipp;
static int *ip;
static volatile int i = 0;
printf("i = %d.\n", i);
ipp = &ip; /* May produce a warning diagnostic */
ipp = (int**) &ip; /* Constraint violation; may produce a warning diagnostic */
*ipp = &i; /* Valid */
if (*ip != 0) { ... | #include <stdio.h>
void func(void) {
static volatile int **ipp;
static volatile int *ip;
static volatile int i = 0;
printf("i = %d.\n", i);
ipp = &ip;
*ipp = &i;
if (*ip != 0) {
/* ... */
}
}
## Compliant Solution
## In this compliant solution,ipis declaredvolatile:
#ccccff
c
#include <stdio.h>... | ## Risk Assessment
Accessing an object with a volatile-qualified type through a reference with a non-volatile-qualified type is
undefined behavior 62
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP32-C
Low
Likely
No
Yes
P6
L2
Automated Detection
Tool
Version
Checker
Description
pointer-qualifier-cas... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,152,129 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152129 | 2 | 3 | EXP33-C | Do not read uninitialized memory | Local, automatic variables assume unexpected values if they are read before they are initialized. The C Standard, 6.7.11, paragraph 11, specifies [
ISO/IEC 9899:2024
]
If an object that has automatic storage duration is not initialized explicitly, its representation is
indeterminate
.
See
undefined behavior 11
.
When l... | void set_flag(int number, int *sign_flag) {
if (NULL == sign_flag) {
return;
}
if (number > 0) {
*sign_flag = 1;
} else if (number < 0) {
*sign_flag = -1;
}
}
int is_negative(int number) {
int sign;
set_flag(number, &sign);
return sign < 0;
}
#include <stdio.h>
/* Get username and passwo... | void set_flag(int number, int *sign_flag) {
if (NULL == sign_flag) {
return;
}
/* Account for number being 0 */
if (number >= 0) {
*sign_flag = 1;
} else {
*sign_flag = -1;
}
}
int is_negative(int number) {
int sign = 0; /* Initialize for defense-in-depth */
set_flag(number, &sign);
ret... | ## Risk Assessment
Reading uninitialized variables is
undefined behavior 20
and can result in
unexpected program behavior
. In some cases, these
security flaws
may allow the execution of arbitrary code.
Reading uninitialized variables for creating entropy is problematic because these memory accesses can be removed by c... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,152,449 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152449 | 2 | 3 | EXP34-C | Do not dereference null pointers | Dereferencing a null pointer is
undefined behavior
.
On many platforms, dereferencing a null pointer results in
abnormal program termination
, but this is not required by the standard. See "
Clever Attack Exploits Fully-Patched Linux Kernel
" [
Goodin 2009
] for an example of a code execution
exploit
that resulted from... | #include <png.h> /* From libpng */
#include <string.h>
void func(png_structp png_ptr, int length, const void *user_data) {
png_charp chunkdata;
chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
/* ... */
memcpy(chunkdata, user_data, length);
/* ... */
}
#include <string.h>
#include <stdlib.h>
voi... | #include <png.h> /* From libpng */
#include <string.h>
void func(png_structp png_ptr, size_t length, const void *user_data) {
png_charp chunkdata;
if (length == SIZE_MAX) {
/* Handle error */
}
if (NULL == user_data) {
/* Handle error */
}
chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
... | ## Risk Assessment
Dereferencing a null pointer is
undefined behavior
, typically
abnormal program termination
. In some situations, however, dereferencing a null pointer can lead to the execution of arbitrary code [
Jack 2007
,
van Sprundel 2006
]. The indicated severity is for this more severe case; on platforms wher... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,152,058 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152058 | 2 | 3 | EXP35-C | Do not modify objects with temporary lifetime | The C11 Standard [
ISO/IEC 9899:2011
] introduced a new term:
temporary lifetime
. This term still remains in the C23 Standard. Modifying an object with temporary lifetime is
undefined behavior
. According to subclause 6.2.4, paragraph 8 [
ISO/IEC 9899:2024
]
A non-lvalue expression with structure or union type, where ... | #include <stdio.h>
struct X { char a[8]; };
struct X salutation(void) {
struct X result = { "Hello" };
return result;
}
struct X addressee(void) {
struct X result = { "world" };
return result;
}
int main(void) {
printf("%s, %s!\n", salutation().a, addressee().a);
return 0;
}
#include <stdio.h>
struct ... | #include <stdio.h>
#if __STDC_VERSION__ < 201112L
#error This code requires a compiler supporting the C11 standard or newer
#endif
struct X { char a[8]; };
struct X salutation(void) {
struct X result = { "Hello" };
return result;
}
struct X addressee(void) {
struct X result = { "world" };
return result;
}
... | ## Risk Assessment
Attempting to modify an array or access it after its lifetime expires may result in erroneous program behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP35-C
Low
Probable
Yes
Yes
P6
L2
Automated Detection
Tool
Version
Checker
Description
temporary-object-modification
Partially... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,152,059 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152059 | 2 | 3 | EXP36-C | Do not cast pointers into more strictly aligned pointer types | Do not convert a pointer value to a pointer type that is more strictly aligned than the referenced type. Different alignments are possible for different types of objects. If the type-checking system is overridden by an explicit cast or the pointer is converted to a void pointer (
void *
) and then to a different type, ... | #include <assert.h>
void func(void) {
char c = 'x';
int *ip = (int *)&c; /* This can lose information */
char *cp = (char *)ip;
/* Will fail on some conforming implementations */
assert(cp == &c);
}
int *loop_function(void *v_pointer) {
/* ... */
return v_pointer;
}
void func(char *char_ptr) {
int... | #include <assert.h>
void func(void) {
char c = 'x';
int i = c;
int *ip = &i;
assert(ip == &i);
}
int *loop_function(int *v_pointer) {
/* ... */
return v_pointer;
}
void func(int *loop_ptr) {
int *int_ptr = loop_function(loop_ptr);
/* ... */
}
#include <string.h>
struct foo_header {
int len;
... | ## Risk Assessment
Accessing a pointer or an object that is not properly aligned can cause a program to crash or give erroneous information, or it can cause slow pointer accesses (if the architecture allows misaligned accesses).
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP36-C
Low
Probable
No
No
P2... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,152,099 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152099 | 2 | 3 | EXP37-C | Call functions with the correct number and type of arguments | Do not call a function with the wrong number or type of arguments.
The C Standard identifies two distinct situations in which
undefined behavior
(UB) may arise as a result of invoking a function using a declaration that is incompatible with its definition or by supplying incorrect types or numbers of arguments:
UB
Desc... | #include <tgmath.h>
void func(void) {
double complex c = 2.0 + 4.0 * I;
double complex result = log2(c);
}
#include <stdio.h>
#include <string.h>
char *(*fp)();
int main(void) {
const char *c;
fp = strchr;
c = fp('e', "Hello");
printf("%s\n", c);
return 0;
}
/* In another source file */
long f(long ... | #include <tgmath.h>
void func(void) {
double complex c = 2.0 + 4.0 * I;
double complex result = log(c)/log(2);
}
#include <tgmath.h>
void func(void) {
double complex c = 2.0 + 4.0 * I;
double complex result = log2(creal(c));
}
#include <stdio.h>
#include <string.h>
char *(*fp)(const char *, int);
int ma... | ## Risk Assessment
Calling a function with incorrect arguments can result in
unexpected
or unintended program behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP37-C
Medium
Probable
No
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
incompatible-argument-type
parameter-match
parame... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,152,294 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152294 | 2 | 3 | EXP39-C | Do not access a variable through a pointer of an incompatible type | Modifying a variable through a pointer of an incompatible type (other than
unsigned char
) can lead to unpredictable results.
Subclause 6.2.7 of the C Standard states that two types may be distinct yet compatible and addresses precisely
when two distinct types are compatible.
This problem is often caused by a violation... | #include <stdio.h>
void f(void) {
if (sizeof(int) == sizeof(float)) {
float f = 0.0f;
int *ip = (int *)&f;
(*ip)++;
printf("float is %f\n", f);
}
}
#include <stdio.h>
void func(void) {
short a[2];
a[0]=0x1111;
a[1]=0x1111;
*(int *)a = 0x22222222;
printf("%x %x\n", a[0], a[1]);
}
#i... | #include <float.h>
#include <math.h>
#include <stdio.h>
void f(void) {
float f = 0.0f;
f = nextafterf(f, FLT_MAX);
printf("float is %f\n", f);
}
#include <stdio.h>
void func(void) {
union {
short a[2];
int i;
} u;
u.a[0]=0x1111;
u.a[1]=0x1111;
u.i = 0x22222222;
printf("%x %x\n", u.a[0],... | ## Risk Assessment
Optimizing for performance can lead to aliasing errors that can be quite difficult to detect. Furthermore, as in the preceding example, unexpected results can lead to buffer overflow attacks, bypassing security checks, or unexpected execution.
Recommendation
Severity
Likelihood
Detectable
Repairable
... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,152,401 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152401 | 2 | 3 | EXP40-C | Do not modify constant objects | The C Standard, 6.7.4, paragraph 7 [
IS
O/IEC 9899:2024
], states
If an attempt is made to modify an object defined with a
const
-qualified type through use of an
lvalue
with non-
const
-qualified type, the behavior is undefined.
See also
undefined behavior 61
.
There are existing compiler
implementations
that allow
co... | const int **ipp;
int *ip;
const int i = 42;
void func(void) {
ipp = &ip; /* Constraint violation */
*ipp = &i; /* Valid */
*ip = 0; /* Modifies constant i (was 42) */
}
## Noncompliant Code Example
## This noncompliant code example allows a constant object to be modified:
#FFcccc
c
const int **ipp;
int *ip;
c... | int **ipp;
int *ip;
int i = 42;
void func(void) {
ipp = &ip; /* Valid */
*ipp = &i; /* Valid */
*ip = 0; /* Valid */
}
## Compliant Solution
The compliant solution depends on the intent of the programmer. If the intent is that the value of
i
is modifiable, then it should not be declared as a constant, as in thi... | ## Risk Assessment
Modifying constant objects through nonconstant references is
undefined behavior 61
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP40-C
Low
Unlikely
Yes
No
P2
L3
Automated Detection
Tool
Version
Checker
Description
assignment-to-non-modifiable-lvalue
pointer-qualifier-cast-const
po... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,151,934 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151934 | 2 | 3 | EXP42-C | Do not compare padding data | The C Standard, 6.7.3.2 paragraph 19 [
ISO/IEC 9899:2024
], states
There may be unnamed padding within a structure object, but not at its beginning. . . . There may be unnamed padding at the end of a structure or union.
Subclause 6.7.11, paragraph 10, states that
unnamed members of objects of structure and union type d... | #include <string.h>
struct s {
char c;
int i;
char buffer[13];
};
void compare(const struct s *left, const struct s *right) {
if ((left && right) &&
(0 == memcmp(left, right, sizeof(struct s)))) {
/* ... */
}
}
## Noncompliant Code Example
In this noncompliant code example,
memcmp()
is used t... | #include <string.h>
struct s {
char c;
int i;
char buffer[13];
};
void compare(const struct s *left, const struct s *right) {
if ((left && right) &&
(left->c == right->c) &&
(left->i == right->i) &&
(0 == memcmp(left->buffer, right->buffer, 13))) {
/* ... */
}
}
## Compliant Solut... | ## Risk Assessment
Comparing padding bytes, when present, can lead to
unexpected program behavior
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP42-C
Medium
Probable
Yes
Yes
P12
L1
Automated Detection
Tool
Version
Checker
Description
memcpy-with-padding
Partially checked
CertC-EXP42
BADFUNC.MEMCMP
U... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,151,927 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151927 | 2 | 3 | EXP43-C | Avoid undefined behavior when using restrict-qualified pointers | An object that is accessed through a
restrict
-qualified pointer has a special association with that pointer. This association requires that all accesses to that object use, directly or indirectly, the value of that particular pointer. The intended use of the
restrict
qualifier is to promote optimization, and deleting ... | null | #include <stdio.h>
void func(void) {
int i;
float x;
int n = scanf("%d%f", &i, &x); /* Defined behavior */
/* ... */
}
void func(void) {
int *restrict p1;
int *restrict q1;
{ /* Added inner block */
int *restrict p2 = p1; /* Valid, well-defined behavior */
int *restrict q2 = q1; /* Va... | ## Risk Assessment
The incorrect use of
restrict
-qualified pointers can result in
undefined behavior 66
that might be
exploited
to cause data integrity violations.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP43-C
Medium
Probable
No
No
P4
L3
Related Vulnerabilities
Search for
vulnerabilities
result... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,152,376 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152376 | 2 | 3 | EXP44-C | Do not rely on side effects in operands to sizeof, _Alignof, or _Generic | Some operators do not evaluate their operands beyond the type information the operands provide. When using one of these operators, do not pass an operand that would otherwise yield a side effect since the side effect will not be generated.
The
sizeof
operator yields the size (in bytes) of its operand, which may be an e... | #include <stdio.h>
void func(void) {
int a = 14;
int b = sizeof(a++);
printf("%d, %d\n", a, b);
}
#include <stddef.h>
#include <stdio.h>
void f(size_t n) {
/* n must be incremented */
size_t a = sizeof(int[++n]);
/* n need not be incremented */
size_t b = sizeof(int[++n % 1 + 1]);
printf("%zu,... | #include <stdio.h>
void func(void) {
int a = 14;
int b = sizeof(a);
++a;
printf("%d, %d\n", a, b);
}
#include <stddef.h>
#include <stdio.h>
void f(size_t n) {
size_t a = sizeof(int[n + 1]);
++n;
size_t b = sizeof(int[n % 1 + 1]);
++n;
printf("%zu, %zu, %zu\n", a, b, n);
/* ... */
}
#include ... | ## Risk Assessment
If expressions that appear to produce side effects are supplied to an operator that does not evaluate its operands, the results may be different than expected. Depending on how this result is used, it can lead to unintended program behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Lev... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,152,228 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152228 | 2 | 3 | EXP45-C | Do not perform assignments in selection statements | Do not use the assignment operator in the contexts listed in the following table because doing so typically indicates programmer error and can result in
unexpected behavior
.
Operator
Context
if
Controlling expression
while
Controlling expression
do ... while
Controlling expression
for
Second operand
?:
First operand
?... | if (a = b) {
/* ... */
}
do { /* ... */ } while (foo(), x = y);
do { /* ... */ } while (x = y, p = q);
while (ch = '\t' || ch == ' ' || ch == '\n') {
/* ... */
}
while ('\t' = ch || ' ' == ch || '\n' == ch) {
/* ... */
}
while ('\t' == ch || ' ' == ch || '\n' == ch) {
/* ... */
}
if ((x = y) != 0) { /* ... | if (a == b) {
/* ... */
}
if ((a = b) != 0) {
/* ... */
}
do { /* ... */ } while (foo(), x == y);
do { /* ... */ } while (foo(), (x = y) != 0);
for (; x; foo(), x = y) { /* ... */ }
do { /* ... */ } while (x = y, p == q);
## Compliant Solution (Unintentional Assignment)
When the assignment of
b
to
a
is not... | null | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,152,216 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152216 | 2 | 3 | EXP46-C | Do not use a bitwise operator with a Boolean-like operand | Mixing bitwise and relational operators in the same full expression can be a sign of a logic error in the expression where a logical operator is usually the intended operator. Do not use the bitwise AND (
&
), bitwise OR (
|
), or bitwise XOR (
^
) operators with an operand of type
_Bool
, or the result of a
relational... | if (getuid() == 0 & getgid() == 0) {
/* ... */
}
## Noncompliant Code Example
## In this noncompliant code example, a bitwise&operator is used with the results of twoequality-expressions:
#FFcccc
c
if (getuid() == 0 & getgid() == 0) {
/* ... */
} | if (getuid() == 0 && getgid() == 0) {
/* ... */
}
## Compliant Solution
## This compliant solution uses the&&operator for the logical operation within the conditional expression:
#ccccff
c
if (getuid() == 0 && getgid() == 0) {
/* ... */
} | ## Risk Assessment
Rule
Severity
Likelihood
Remediation Cost
Priority
Level
EXP46-C
Low
Likely
Low
P9
L2
Automated Detection
Tool
Version
Checker
Description
bitwise-operator-with-boolean-like-operand
Fully checked
CertC-EXP46
LANG.TYPE.IOT
Inappropriate operand type
CONSTANT_EXPRESSION_RESULT
Partially implemented
bit... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,151,991 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151991 | 2 | 3 | EXP47-C | Do not call va_arg with an argument of the incorrect type | The variable arguments passed to a variadic function are accessed by calling the
va_arg()
macro. This macro accepts the
va_list
representing the variable arguments of the function invocation and the type denoting the expected argument type for the argument being retrieved. The macro is typically invoked within a loop, ... | #include <stdarg.h>
#include <stddef.h>
void func(size_t num_vargs, ...) {
va_list ap;
va_start(ap, num_vargs);
if (num_vargs > 0) {
unsigned char c = va_arg(ap, unsigned char);
// ...
}
va_end(ap);
}
void f(void) {
unsigned char c = 0x12;
func(1, c);
}
#include <stdarg.h>
void func(const ... | #include <stdarg.h>
#include <stddef.h>
void func(size_t num_vargs, ...) {
va_list ap;
va_start(ap, num_vargs);
if (num_vargs > 0) {
unsigned char c = (unsigned char) va_arg(ap, int);
// ...
}
va_end(ap);
}
void f(void) {
unsigned char c = 0x12;
func(1, c);
}
#include <stdarg.h>
#include <std... | ## Risk Assessment
Incorrect use of
va_arg()
results in undefined behavior that can include accessing stack memory.
Rule
Severity
Likelihood
Remediation Cost
Priority
Level
EXP47-C
Medium
Likely
High
P6
L2
Automated Detection
Tool
Version
Checker
Description
CertC-EXP47
-Wvarargs
Can detect some instances of this rule,... | SEI CERT C Coding Standard > 2 Rules > Rule 03. Expressions (EXP) |
c | 87,152,403 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152403 | 3 | 9 | FIO01-C | Be careful using functions that use file names for identification | Many file-related security vulnerabilities result from a program accessing an unintended file object because file names are only loosely bound to underlying file objects. File names provide no information regarding the nature of the file object itself. Furthermore, the binding of a file name to a file object is reasser... | char *file_name;
FILE *f_ptr;
/* Initialize file_name */
f_ptr = fopen(file_name, "w");
if (f_ptr == NULL) {
/* Handle error */
}
/*... Process file ...*/
if (fclose(f_ptr) != 0) {
/* Handle error */
}
if (remove(file_name) != 0) {
/* Handle error */
}
char *file_name;
FILE *f_ptr;
/* Initialize file_name ... | char *file_name;
int fd;
/* Initialize file_name */
fd = open(
file_name,
O_WRONLY | O_CREAT | O_EXCL,
S_IRWXU
);
if (fd == -1) {
/* Handle error */
}
/* ... */
if (fchmod(fd, S_IRUSR) == -1) {
/* Handle error */
}
## Compliant Solution
Not much can be done programmatically to ensure the file removed is ... | ## Risk Assessment
Many file-related vulnerabilities, such as
time-of-check, time-of-use
(TOCTOU)
race conditions, can be exploited to cause a program to access an unintended file. Using
FILE
pointers or file descriptors to identify files instead of file names reduces the chance of accessing an unintended file. Remedia... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,398 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152398 | 3 | 9 | FIO02-C | Canonicalize path names originating from tainted sources | Path names, directory names, and file names may contain characters that make
validation
difficult and inaccurate. Furthermore, any path name component can be a symbolic link, which further obscures the actual location or identity of a file. To simplify file name validation, it is recommended that names be translated in... | /* Verify argv[1] is supplied */
if (!verify_file(argv[1])) {
/* Handle error */
}
if (fopen(argv[1], "w") == NULL) {
/* Handle error */
}
/* ... */
char *realpath_res = NULL;
char *canonical_filename = NULL;
size_t path_size = 0;
long pc_result;
/* Verify argv[1] is supplied */
errno = 0;
/* Query for PATH_... | #if _POSIX_VERSION >= 200809L || defined (linux)
char *realpath_res = NULL;
/* Verify argv[1] is supplied */
realpath_res = realpath(argv[1], NULL);
if (realpath_res == NULL) {
/* Handle error */
}
if (!verify_file(realpath_res)) {
/* Handle error */
}
if (fopen(realpath_res, "w") == NULL) {
/* Handle error ... | ## Risk Assessment
File-related
vulnerabilities
can often be
exploited
to cause a program with elevated privileges to access an unintended file. Canonicalizing a file path makes it easier to identify the reference file object.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO02-C
Medium
Probab... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,382 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152382 | 3 | 9 | FIO03-C | Do not make assumptions about fopen() and file creation | The C
fopen()
function is used to open an existing file or create a new one. The C11 version of the
fopen()
function provides a mode flag,
x
, that provides the mechanism needed to determine if the file that is to be opened exists. Not using this mode flag can lead to a program overwriting or accessing an unintended fi... | char *file_name;
FILE *fp;
/* Initialize file_name */
fp = fopen(file_name, "w");
if (!fp) {
/* Handle error */
}
## Noncompliant Code Example (fopen())
In this noncompliant code example, the file referenced by
file_name
is opened for writing. This example is noncompliant if the programmer's intent was to create a... | char *file_name;
FILE *fp;
/* Initialize file_name */
fp = fopen(file_name, "wx");
if (!fp) {
/* Handle error */
}
char *file_name;
int new_file_mode;
/* Initialize file_name and new_file_mode */
int fd = open(file_name, O_CREAT | O_EXCL | O_WRONLY, new_file_mode);
if (fd == -1) {
/* Handle error */
}
char *f... | ## Risk Assessment
The ability to determine whether an existing file has been opened or a new file has been created provides greater assurance that a file other than the intended file is not acted upon.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO03-C
Medium
Probable
No
No
P4
L3
Automated... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,439 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152439 | 3 | 9 | FIO05-C | Identify files using multiple file attributes | Files can often be identified by attributes other than the file name, such as by comparing file ownership or creation time. Information about a file that has been created and closed can be stored and then used to validate the identity of the file when it is reopened.
Comparing multiple attributes of the file increases ... | char *file_name;
/* Initialize file_name */
FILE *fd = fopen(file_name, "w");
if (fd == NULL) {
/* Handle error */
}
/*... Write to file ...*/
fclose(fd);
fd = NULL;
/*
* A race condition here allows for an attacker
* to switch out the file for another.
*/
/* ... */
fd = fopen(file_name, "r");
if (fd == ... | struct stat orig_st;
struct stat new_st;
char *file_name;
/* Initialize file_name */
int fd = open(file_name, O_WRONLY);
if (fd == -1) {
/* Handle error */
}
/*... Write to file ...*/
if (fstat(fd, &orig_st) == -1) {
/* Handle error */
}
close(fd);
fd = -1;
/* ... */
fd = open(file_name, O_RDONLY);
if (fd == ... | ## Risk Assessment
Many file-related
vulnerabilities
are exploited to cause a program to access an unintended file. Proper file identification is necessary to prevent
exploitation
.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO05-C
Medium
Probable
No
No
P4
L3
Automated Detection
Tool
Versi... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,391 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152391 | 3 | 9 | FIO06-C | Create files with appropriate access permissions | Creating a file with insufficiently restrictive access permissions may allow an unprivileged user to access that file. Although access permissions are heavily dependent on the file system, many file-creation functions provide mechanisms to set (or at least influence) access permissions. When these functions are used to... | char *file_name;
FILE *fp;
/* Initialize file_name */
fp = fopen(file_name, "w");
if (!fp){
/* Handle error */
}
requested_permissions = 0666;
actual_permissions = requested_permissions & ~umask();
char *file_name;
int fd;
/* Initialize file_name */
fd = open(file_name, O_CREAT | O_WRONLY);
/* Access permission... | char *file_name;
int file_access_permissions;
/* Initialize file_name and file_access_permissions */
int fd = open(
file_name,
O_CREAT | O_WRONLY,
file_access_permissions
);
if (fd == -1){
/* Handle error */
}
## Compliant Solution (open(), POSIX)
Access permissions for the newly created file should be speci... | ## Risk Assessment
Creating files with weak access permissions may allow unintended access to those files.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO06-C
Medium
Probable
No
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
BADFUNC.CREATEFILE
(customization)
Use of CreateFile... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,067 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152067 | 3 | 9 | FIO08-C | Take care when calling remove() on an open file | Invoking
remove()
on an open file is
implementation-defined
. Removing an open file is sometimes recommended to hide the names of temporary files that may be prone to attack. (See
.)
In cases requiring the removal of an open file, a more strongly defined function, such as the POSIX
unlink()
function, should be consider... | char *file_name;
FILE *file;
/* Initialize file_name */
file = fopen(file_name, "w+");
if (file == NULL) {
/* Handle error condition */
}
/* ... */
if (remove(file_name) != 0) {
/* Handle error condition */
}
/* Continue performing I/O operations on file */
fclose(file);
## Noncompliant Code Example
## This ... | FILE *file;
char *file_name;
/* Initialize file_name */
file = fopen(file_name, "w+");
if (file == NULL) {
/* Handle error condition */
}
if (unlink(file_name) != 0) {
/* Handle error condition */
}
/* Continue performing I/O operations on file */
fclose(file);
## Compliant Solution (POSIX)
This compliant sol... | ## Risk Assessment
Calling
remove()
on an open file has different implications for different implementations and may cause
abnormal termination
if the removed file is written to or read from, or it may result in unintended information disclosure from files not deleted as intended.
Recommendation
Severity
Likelihood
Det... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,342 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152342 | 3 | 9 | FIO09-C | Be careful with binary data when transferring data across systems | Portability is a concern when using the
fread()
and
fwrite()
functions across multiple, heterogeneous systems. In particular, it is never guaranteed that reading or writing of scalar data types such as integers, let alone aggregate types such as arrays or structures, will preserve the representation or value of the dat... | struct myData {
char c;
long l;
};
/* ... */
FILE *file;
struct myData data;
/* Initialize file */
if (fread(&data, sizeof(struct myData), 1, file) < sizeof(struct myData)) {
/* Handle error */
}
## Noncompliant Code Example
## This noncompliant code example reads data from a file stream into a data structur... | struct myData {
char c;
long l;
};
/* ... */
FILE *file;
struct myData data;
char buf[25];
char *end_ptr;
/* Initialize file */
if (fgets(buf, 1, file) == NULL) {
/* Handle error */
}
data.c = buf[0];
if (fgets(buf, sizeof(buf), file) == NULL) {
/* Handle Error */
}
data.l = strtol(buf, &end_ptr, 10);
i... | ## Risk Assessment
Reading binary data that has a different format than expected may result in unintended program behavior.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO09-C
Medium
Probable
No
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
Compass/ROSE
Could flag possible vi... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,143 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152143 | 3 | 9 | FIO10-C | Take care when using the rename() function | The
rename()
function has the following prototype:
int rename(const char *src_file, const char *dest_file);
If the file referenced by
dest_file
exists prior to calling
rename()
, the behavior is
implementation-defined
. On POSIX systems, the destination file is removed. On Windows systems, the
rename()
fails. Consequen... | const char *src_file = /* ... */;
const char *dest_file = /* ... */;
if (rename(src_file, dest_file) != 0) {
/* Handle error */
}
const char *src_file = /* ... */;
const char *dest_file = /* ... */;
if (rename(src_file, dest_file) != 0) {
/* Handle error */
}
## Noncompliant Code Example (POSIX)
## This code exam... | const char *src_file = /* ... */;
const char *dest_file = /* ... */;
if (access(dest_file, F_OK) != 0) {
if (rename(src_file, dest_file) != 0) {
/* Handle error condition */
}
}
else {
/* Handle file-exists condition */
}
const char *src_file = /* ... */;
const char *dest_file = /* ... */;
if (rename(src_f... | ## Risk Assessment
Calling
rename()
has
implementation-defined
behavior when the new file name refers to an existing file. Incorrect use of
rename()
can result in a file being unexpectedly overwritten or other
unexpected behavior
.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO10-C
Medium
P... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,174 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152174 | 3 | 9 | FIO11-C | Take care when specifying the mode parameter of fopen() | The C Standard identifies specific strings to use for the
mode
on calls to
fopen()
and
fopen_s()
. C11 provides a new mode flag,
x
, that provides the mechanism needed to determine if the file that is to be opened exists. To be strictly
conforming
and portable, one of the strings from the following table (adapted from ... | null | null | ## Risk Assessment
Using a
mode
string that is not recognized by an implementation may cause the call to
fopen()
to fail.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO11-C
Medium
Probable
No
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
fopen-mode
fopen-s-mode
Partially che... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,185 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152185 | 3 | 9 | FIO13-C | Never push back anything other than one read character | Subclause 7.21.7.10 of the C Standard [
ISO/IEC 9899:2011
] defines
ungetc()
as follows:
The
ungetc
function pushes the character specified by
c
(converted to an
unsigned char
) back onto the input stream pointed to by
stream
. Pushed-back characters will be returned by subsequent reads on that stream in the reverse or... | FILE *fp;
char *file_name;
/* Initialize file_name */
fp = fopen(file_name, "rb");
if (fp == NULL) {
/* Handle error */
}
/* Read data */
if (ungetc('\n', fp) == EOF) {
/* Handle error */
}
if (ungetc('\r', fp) == EOF) {
/* Handle error */
}
/* Continue */
## Noncompliant Code Example
## In this noncomplian... | FILE *fp;
fpos_t pos;
char *file_name;
/* Initialize file_name */
fp = fopen(file_name, "rb");
if (fp == NULL) {
/* Handle error */
}
/* Read data */
if (fgetpos(fp, &pos)) {
/* Handle error */
}
/* Read the data that will be "pushed back" */
if (fsetpos(fp, &pos)) {
/* Handle error */
}
/* Continue */
##... | ## Risk Assessment
If used improperly,
ungetc()
and
ungetwc()
can cause data to be truncated or lost.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO13-C
Medium
Probable
No
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
(customization)
Users can implement a custom check that t... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,146 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152146 | 3 | 9 | FIO14-C | Understand the difference between text mode and binary mode with file streams | Input and output are mapped into logical data streams whose properties are more uniform than their various inputs and outputs. Two forms of mapping are supported, one for text streams and one for binary streams. They differ in the actual representation of data as well as in the functionality of some C functions.
Text S... | null | null | ## Risk Assessment
Failure to understand file stream mappings can result in unexpectedly formatted files.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO14-C
Low
Probable
No
No
P2
L3
Related Vulnerabilities
Search for
vulnerabilities
resulting from the violation of this rule on the
CERT webs... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,134 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152134 | 3 | 9 | FIO15-C | Ensure that file operations are performed in a secure directory | File operations should be performed in a
secure directory
. In most cases, a secure directory is a directory in which no one other than the user, or possibly the administrator, has the ability to create, rename, delete, or otherwise manipulate files. (Other users may read or search the directory but generally may not m... | char *file_name;
FILE *fp;
/* Initialize file_name */
fp = fopen(file_name, "w");
if (fp == NULL) {
/* Handle error */
}
/* ... Process file ... */
if (fclose(fp) != 0) {
/* Handle error */
}
if (remove(file_name) != 0) {
/* Handle error */
}
% cd /tmp/app/
% rm -rf tmpdir
% ln -s /etc tmpdir
## Noncompli... | #include <stdlib.h>
#include <limits.h>
#include <string.h>
#include <libgen.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
enum { MAX_SYMLINKS = 5 };
/* Returns nonzero if directory is secure, zero otherwise */
int secure_dir(const char *fullpath) {
static unsigned int num_symlinks = 0;
char... | ## Risk Assessment
Failing to perform file I/O operations in a secure directory that cannot otherwise be securely performed can result in a broad range of file system vulnerabilities.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO15-C
Medium
Probable
No
No
P4
L3
Related Vulnerabilities
Sear... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,233 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152233 | 3 | 9 | FIO17-C | Do not rely on an ending null character when using fread() | The
fread()
function, as defined in the C Standard, subclause 7.21.8.1 [
ISO/IEC 9899:2011
], does not explicitly null-terminate the read character sequence.
Synopsis
size_t fread(void * restrict ptr, size_t size, size_t nmemb, FILE * restrict stream)
Description
The
fread
function reads, into the array pointed to by
p... | #include <stdio.h>
#include <stdlib.h>
int main (void) {
FILE *fp;
size_t size;
long length;
char *buffer;
fp = fopen("file.txt", "rb");
if (fp == NULL) {
/* Handle file open error */
}
/* Obtain file size */
if (fseek(fp, 0, SEEK_END) != 0) {
/* Handle repositioning... | #include <stdio.h>
#include <stdlib.h>
int main (void) {
FILE *fp;
size_t size;
long length;
char *buffer;
fp = fopen("file.txt", "rb");
if (fp == NULL) {
/* Handle file open error */
}
/* Obtain file size */
if (fseek(fp, 0, SEEK_END) != 0) {
/* Handle repositioning... | ## Risk Assessment
When reading an input stream, the read character sequence is not explicitly null-terminated by the
fread()
function. Operations on the read-to buffer could result in overruns, causing
abnormal program termination
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO17-C
Low
Likely
No
Ye... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,250 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152250 | 3 | 9 | FIO18-C | Never expect fwrite() to terminate the writing process at a null character | The C Standard, subclause 7.21.8.2 [
ISO/IEC 9899:2011
], defines the
fwrite()
function as follows:
Synopsis
size_t fwrite(const void *restrict ptr, size_t size, size_t nmemb, FILE *restrict stream);
Description
The
fwrite()
function writes, from the array pointed to by
ptr
, up to
nmemb
elements whose size is specifie... | #include <stdio.h>
#include <stdlib.h>
char *buffer = NULL;
size_t size1;
size_t size2;
FILE *filedes;
/* Assume size1 and size2 are appropriately initialized */
filedes = fopen("out.txt", "w+");
if (filedes == NULL) {
/* Handle error */
}
buffer = (char *)calloc( 1, size1);
if (buffer == NULL) {
/* Handle error... | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *buffer = NULL;
size_t size1;
size_t size2;
FILE *filedes;
/* Assume size1 is appropriately initialized */
filedes = fopen("out.txt", "w+");
if (filedes == NULL){
/* Handle error */
}
buffer = (char *)calloc( 1, size1);
if (buffer == NULL) {
/* Ha... | ## Risk Assessment
Failure to follow the recommendation could result in a non-null-terminated string being written to a file, which will create problems when the program tries to read it back as a null-terminated byte string.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO18-C
Medium
Probabl... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,291 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152291 | 3 | 9 | FIO19-C | Do not use fseek() and ftell() to compute the size of a regular file | Understanding the difference between text mode and binary mode is important when using functions that operate on file streams. (See
for more information.)
Subclause 7.21.9.2 of the C Standard [
ISO/IEC 9899:2011
] specifies the following behavior for
fseek()
when opening a binary file in binary mode:
A binary stream ne... | FILE *fp;
long file_size;
char *buffer;
fp = fopen("foo.bin", "rb");
if (fp == NULL) {
/* Handle error */
}
if (fseek(fp, 0 , SEEK_END) != 0) {
/* Handle error */
}
file_size = ftell(fp);
if (file_size == -1) {
/* Handle error */
}
buffer = (char*)malloc(file_size);
if (buffer == NULL) {
/* Handle error */
... | FILE* fp;
int fd;
off_t file_size;
char *buffer;
struct stat st;
fd = open("foo.bin", O_RDONLY);
if (fd == -1) {
/* Handle error */
}
fp = fdopen(fd, "r");
if (fp == NULL) {
/* Handle error */
}
/* Ensure that the file is a regular file */
if ((fstat(fd, &st) != 0) || (!S_ISREG(st.st_mode))) {
/* Handle erro... | ## Risk Assessment
Understanding the difference between text mode and binary mode with file streams is critical when working with functions that operate on them. Setting the file position indicator to end-of-file with
fseek()
has
undefined behavior
for a binary stream. In addition, the return value of
ftell()
for strea... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,445 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152445 | 3 | 9 | FIO20-C | Avoid unintentional truncation when using fgets() or fgetws() | The
fgets()
and
fgetws()
functions are typically used to read a newline-terminated line of input from a stream. Both functions read at most one less than the number of narrow or wide characters specified by an argument
n
from a stream to a string. Truncation errors can occur if
n - 1
is less than the number of characte... | #include <stdbool.h>
#include <stdio.h>
bool get_data(char *buffer, int size) {
if (fgets(buffer, size, stdin)) {
return true;
}
return false;
}
void func(void) {
char buf[8];
if (get_data(buf, sizeof(buf))) {
printf("The user input %s\n", buf);
} else {
printf("Error getting data from the u... | #include <stdbool.h>
#include <stdio.h>
#include <string.h>
bool get_data(char *buffer, int size) {
if (fgets(buffer, size, stdin)) {
size_t len = strlen(buffer);
return feof(stdin) || (len != 0 && buffer[len-1] == '\n');
}
return false;
}
void func(void) {
char buf[8];
if (get_data(buf, sizeof(bu... | ## Risk Assessment
Incorrectly assuming a newline character is read by
fgets()
or
fgetws()
can result in data truncation.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO20-C
Medium
Likely
No
Yes
P12
L1
Automated Detection
Tool
Version
Checker
Description
C3591
C3592
LDRA tool suite
44 S
Enha... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,425 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152425 | 3 | 9 | FIO21-C | Do not create temporary files in shared directories | Programmers frequently create temporary files in directories that are writable by everyone (examples are
/tmp
and
/var/tmp
on UNIX and
%TEMP%
on Windows) and may be purged regularly (for example, every night or during reboot).
Temporary files are commonly used for auxiliary storage for data that does not need to, or ot... | #include <stdio.h>
void func(const char *file_name) {
FILE *fp = fopen(file_name, "wb+");
if (fp == NULL) {
/* Handle error */
}
}
#include <stdio.h>
void func(void) {
char file_name[L_tmpnam];
FILE *fp;
if (!tmpnam(file_name)) {
/* Handle error */
}
/* A TOCTOU race condition exists here... | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
extern int secure_dir(const char *sdn);
void func(void) {
const char *sdn = "/home/usr1/";
char sfn[] = "/home/usr1/temp-XXXXXX";
FILE *sfp;
if (!secure_dir(sdn)) {
/* Handle error */
}
int fd = mkstemp(sfn);
if (fd == -1) {
/* Handl... | ## Risk Assessment
Insecure temporary file creation can lead to a program accessing unintended files and permission escalation on local systems.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO21-C
Medium
Probable
No
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
BADFUNC.TEMP.*... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,114 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152114 | 3 | 9 | FIO22-C | Close files before spawning processes | Standard
FILE
objects and their underlying representation (file descriptors on POSIX platforms or handles elsewhere) are a finite resource that must be carefully managed. The number of files that an
implementation
guarantees may be open simultaneously is bounded by the
FOPEN_MAX
macro defined in
<stdio.h>
. The value o... | #include <stdio.h>
#include <stdlib.h>
extern const char *get_validated_editor(void);
void func(const char *file_name) {
FILE *f;
const char *editor;
f = fopen(file_name, "r");
if (f == NULL) {
/* Handle error */
}
editor = get_validated_editor();
if (editor == NULL) {
/* Handle error */
... | #include <stdio.h>
#include <stdlib.h>
extern const char *get_validated_editor(void);
void func(const char *file_name) {
FILE *f;
const char *editor;
f = fopen(file_name, "r");
if (f == NULL) {
/* Handle error */
}
fclose(f);
f = NULL;
editor = get_validated_editor();
if (editor == NULL... | ## Risk Assessment
Failing to properly close files may allow unintended access to, or exhaustion of, system resources.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO22-C
Medium
Unlikely
No
No
P2
L3
Automated Detection
Tool
Version
Checker
Description
Compass/ROSE
RH.LEAK
LDRA tool suite
49 D
Partiall... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,151,957 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151957 | 3 | 9 | FIO23-C | Do not exit with unflushed data in stdout or stderr | Deprecated
This guideline does not apply to code that need conform only to C23. Code that must conform to older versions of the C standard should still comply with this guideline.
The C standard makes no guarantees as to when output to
stdout
(standard output) or
stderr
(standard error) is actually flushed. On many pla... | #include <stdio.h>
int main(void) {
printf("Hello, world!\n");
return 0;
}
#include <stdio.h>
void cleanup(void) {
/* Do cleanup */
printf("All cleaned up!\n");
}
int main(void) {
atexit(cleanup);
printf("Doing important stuff\n");
/* Do important stuff */
if (fclose(stdout) == EOF) {
/* Ha... | #include <stdio.h>
int main(void) {
printf("Hello, world!\n");
if (fclose(stdout) == EOF) {
/* Handle error */
}
return 0;
}
#include <stdio.h>
void cleanup(void) {
/* Do cleanup */
printf("All cleaned up!\n");
if (fflush(stdout) == EOF) {
/* Handle error */
}
}
int main(void) {
atexit(... | ## Risk Assessment
Failing to flush data buffered for standard output or standard error may result in lost data.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO23-C
Medium
Unlikely
No
Yes
P4
L3
Related Vulnerabilities
Search for
vulnerabilities
resulting from the violation of this rule on th... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,138 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152138 | 3 | 9 | FIO24-C | Do not open a file that is already open | Opening a file that is already open has
implementation-defined behavior
, according to the C Standard, 7.21.3, paragraph 8 [
ISO/IEC 9899:2011
]:
Functions that open additional (nontemporary) files require a file name, which is a string. The rules for composing valid file names are implementation-defined. Whether the same... | #include <stdio.h>
void do_stuff(void) {
FILE *logfile = fopen("log", "a");
if (logfile == NULL) {
/* Handle error */
}
/* Write logs pertaining to do_stuff() */
fprintf(logfile, "do_stuff\n");
}
int main(void) {
FILE *logfile = fopen("log", "a");
if (logfile == NULL) {
/* Handle error */
}
... | #include <stdio.h>
void do_stuff(FILE *logfile) {
/* Write logs pertaining to do_stuff() */
fprintf(logfile, "do_stuff\n");
}
int main(void) {
FILE *logfile = fopen("log", "a");
if (logfile == NULL) {
/* Handle error */
}
/* Write logs pertaining to main() */
fprintf(logfile, "main\n");
do_stuf... | ## Risk Assessment
Simultaneously opening a file multiple times can result in unexpected errors and nonportable behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO24-C
Medium
Probable
No
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
IO.RACE
(customization)
IO.BRAW
File system rac... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 09. Input Output (FIO) |
c | 87,152,197 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152197 | 2 | 9 | FIO30-C | Exclude user input from format strings | Never call a formatted I/O function with a format string containing a
tainted value
. An attacker who can fully or partially control the contents of a format string can crash a vulnerable process, view the contents of the stack, view memory content, or write to an arbitrary memory location. Consequently, the attacker ... | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void incorrect_password(const char *user) {
int ret;
/* User names are restricted to 256 or fewer characters */
static const char msg_format[] = "%s cannot be authenticated.\n";
size_t len = strlen(user) + sizeof(msg_format);
char *msg = (char *)mal... | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
void incorrect_password(const char *user) {
int ret;
/* User names are restricted to 256 or fewer characters */
static const char msg_format[] = "%s cannot be authenticated.\n";
size_t len = strlen(user) + sizeof(msg_format);
char *msg = (char *)mal... | ## Risk Assessment
Failing to exclude user input from format specifiers may allow an attacker to crash a vulnerable process, view the contents of the stack, view memory content, or write to an arbitrary memory location and consequently execute arbitrary code with the permissions of the vulnerable process.
Rule
Severity... | SEI CERT C Coding Standard > 2 Rules > Rule 09. Input Output (FIO) |
c | 87,152,343 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152343 | 2 | 9 | FIO32-C | Do not perform operations on devices that are only appropriate for files | File names on many operating systems, including Windows and UNIX, may be used to access
special files
, which are actually devices. Reserved Microsoft Windows device names include
AUX
,
CON
,
PRN
,
COM1
, and
LPT1
or paths using the
\\.\
device namespace. Device files on UNIX systems are used to apply access rights and... | #include <stdio.h>
void func(const char *file_name) {
FILE *file;
if ((file = fopen(file_name, "wb")) == NULL) {
/* Handle error */
}
/* Operate on the file */
if (fclose(file) == EOF) {
/* Handle error */
}
}
#include <Windows.h>
void func(const TCHAR *file_name) {
HANDLE hFile = CreateFil... | #include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#ifdef O_NOFOLLOW
#define OPEN_FLAGS O_NOFOLLOW | O_NONBLOCK
#else
#define OPEN_FLAGS O_NONBLOCK
#endif
void func(const char *file_name) {
struct stat orig_st;
struct stat open_st;
int fd;
int flags;
if ((lstat(file_nam... | ## Risk Assessment
Allowing operations that are appropriate only for regular files to be performed on devices can result in
denial-of-service attacks
or more serious
exploits
depending on the platform.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO32-C
Medium
Unlikely
No
No
P2
L3
Automated Detection
... | SEI CERT C Coding Standard > 2 Rules > Rule 09. Input Output (FIO) |
c | 87,151,948 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151948 | 2 | 9 | FIO34-C | Distinguish between characters read from a file and EOF or WEOF | The
EOF
macro represents a negative value that is used to indicate that the file is exhausted and no data remains when reading data from a file.
EOF
is an example of an
in-band error indicator
. In-band error indicators are problematic to work with, and the creation of new in-band-error indicators is discouraged by
.
T... | #include <stdio.h>
void func(void) {
int c;
do {
c = getchar();
} while (c != EOF);
}
#include <assert.h>
#include <limits.h>
#include <stdio.h>
void func(void) {
char c;
static_assert(UCHAR_MAX < UINT_MAX, "FIO34-C violation");
do {
c = getchar();
} while (c != EOF);
}
#include <stddef.h>... | #include <stdio.h>
void func(void) {
int c;
do {
c = getchar();
} while (c != EOF || (!feof(stdin) && !ferror(stdin)));
}
#include <assert.h>
#include <stdio.h>
#include <limits.h>
void func(void) {
int c;
static_assert(UCHAR_MAX < UINT_MAX, "FIO34-C violation");
do {
c = getchar();
} while (... | ## Risk Assessment
Incorrectly assuming characters from a file cannot match
EOF
or
WEOF
has resulted in significant vulnerabilities, including command injection attacks. (See the
*CA-1996-22
advisory.)
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO34-C
High
Probable
Yes
Yes
P18
L1
Automated Detection... | SEI CERT C Coding Standard > 2 Rules > Rule 09. Input Output (FIO) |
c | 87,152,422 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152422 | 2 | 9 | FIO37-C | Do not assume that fgets() or fgetws() returns a nonempty string when successful | Errors can occur when incorrect assumptions are made about the type of data being read. These assumptions may be violated, for example, when binary data has been read from a file instead of text from a user's terminal or the output of a process is piped to
stdin.
(See
.) On some systems, it may also be possible to inpu... | #include <stdio.h>
#include <string.h>
enum { BUFFER_SIZE = 1024 };
void func(void) {
char buf[BUFFER_SIZE];
if (fgets(buf, sizeof(buf), stdin) == NULL) {
/* Handle error */
}
buf[strlen(buf) - 1] = '\0';
}
## Noncompliant Code Example
This noncompliant code example attempts to remove the trailing newl... | #include <stdio.h>
#include <string.h>
enum { BUFFER_SIZE = 1024 };
void func(void) {
char buf[BUFFER_SIZE];
char *p;
if (fgets(buf, sizeof(buf), stdin)) {
p = strchr(buf, '\n');
if (p) {
*p = '\0';
}
} else {
/* Handle error */
}
}
## Compliant Solution
## This compliant solution u... | ## Risk Assessment
Incorrectly assuming that character data has been read can result in an out-of-bounds memory write or other flawed logic.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO37-C
High
Probable
Yes
Yes
P18
L1
Automated Detection
Tool
Version
Checker
Description
Supported: Astrée reports d... | SEI CERT C Coding Standard > 2 Rules > Rule 09. Input Output (FIO) |
c | 87,152,442 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152442 | 2 | 9 | FIO38-C | Do not copy a FILE object | According to the C Standard, 7.23.3, paragraph 6 [
ISO/IEC 9899:2024
],
The address of the
FILE
object used to control a stream may be significant; a copy of a
FILE
object is not required to serve in place of the original.
Consequently, do not copy a
FILE
object. | #include <stdio.h>
int main(void) {
FILE my_stdout = *stdout;
if (fputs("Hello, World!\n", &my_stdout) == EOF) {
/* Handle error */
}
return 0;
}
## Noncompliant Code Example
## This noncompliant code example can fail because a by-value copy ofstdoutis being used in the call tofputs():
#FFCCCC
c
#include... | #include <stdio.h>
int main(void) {
FILE *my_stdout = stdout;
if (fputs("Hello, World!\n", my_stdout) == EOF) {
/* Handle error */
}
return 0;
}
## Compliant Solution
## In this compliant solution, a copy of thestdoutpointer to theFILEobject is used in the call tofputs():
#ccccff
c
#include <stdio.h>
int... | ## Risk Assessment
Using a copy of a
FILE
object in place of the original may result in a crash, which can be used in a
denial-of-service attack
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO38-C
Low
Probable
Yes
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
file-dereference
Partial... | SEI CERT C Coding Standard > 2 Rules > Rule 09. Input Output (FIO) |
c | 87,152,175 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152175 | 2 | 9 | FIO39-C | Do not alternately input and output from a stream without an intervening flush or positioning call | The C Standard, 7.23.5.3, paragraph 7 [
ISO/IEC 9899:2024
], places the following restrictions on update streams:
When a file is opened with update mode . . ., both input and output may be performed on the associated stream. However, output shall not be directly followed by input without an intervening call to the
fflu... | #include <stdio.h>
enum { BUFFERSIZE = 32 };
extern void initialize_data(char *data, size_t size);
void func(const char *file_name) {
char data[BUFFERSIZE];
char append_data[BUFFERSIZE];
FILE *file;
file = fopen(file_name, "a+");
if (file == NULL) {
/* Handle error */
}
initialize_data(append_... | #include <stdio.h>
enum { BUFFERSIZE = 32 };
extern void initialize_data(char *data, size_t size);
void func(const char *file_name) {
char data[BUFFERSIZE];
char append_data[BUFFERSIZE];
FILE *file;
file = fopen(file_name, "a+");
if (file == NULL) {
/* Handle error */
}
initialize_data(append_da... | ## Risk Assessment
Alternately inputting and outputting from a stream without an intervening flush or positioning call is
undefined behavior 156
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO39-C
Low
Likely
Yes
No
P6
L2
Automated Detection
Tool
Version
Checker
Description
Supported, but no explicit... | SEI CERT C Coding Standard > 2 Rules > Rule 09. Input Output (FIO) |
c | 87,152,165 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152165 | 2 | 9 | FIO40-C | Reset strings on fgets() or fgetws() failure | If either of the C Standard
fgets()
or
fgetws()
functions fail, the contents of the array being written is
indeterminate
. (See
undefined behavior 175
.) It is necessary to reset the string to a known value to avoid errors on subsequent string manipulation functions. | #include <stdio.h>
enum { BUFFER_SIZE = 1024 };
void func(FILE *file) {
char buf[BUFFER_SIZE];
if (fgets(buf, sizeof(buf), file) == NULL) {
/* Set error flag and continue */
}
}
## Noncompliant Code Example
In this noncompliant code example, an error flag is set if
fgets()
fails. However,
buf
is not reset... | #include <stdio.h>
enum { BUFFER_SIZE = 1024 };
void func(FILE *file) {
char buf[BUFFER_SIZE];
if (fgets(buf, sizeof(buf), file) == NULL) {
/* Set error flag and continue */
*buf = '\0';
}
}
## Compliant Solution
In this compliant solution,
buf
is set to an empty string if
fgets()
fails. The equivale... | ## Risk Assessment
Making invalid assumptions about the contents of an array modified by
fgets()
or
fgetws()
can result in
undefined behavior 175
and
abnormal program termination
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO40-C
Low
Probable
Yes
Yes
P6
L2
Automated Detection
Tool
Version
Checker
D... | SEI CERT C Coding Standard > 2 Rules > Rule 09. Input Output (FIO) |
c | 87,152,189 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152189 | 2 | 9 | FIO41-C | Do not call getc(), putc(), getwc(), or putwc() with a stream argument that has side effects | Do not invoke
getc()
or
putc()
or their wide-character analogues
getwc()
and
putwc()
with a stream argument that has side effects. The stream argument passed to these macros may be evaluated more than once if these functions are implemented as unsafe macros. (See
for more information.)
This rule does not apply to the c... | #include <stdio.h>
void func(const char *file_name) {
FILE *fptr;
int c = getc(fptr = fopen(file_name, "r"));
if (feof(fptr) || ferror(fptr)) {
/* Handle error */
}
if (fclose(fptr) == EOF) {
/* Handle error */
}
}
#include <stdio.h>
void func(const char *file_name) {
FILE *fptr = NULL;
i... | #include <stdio.h>
void func(const char *file_name) {
int c;
FILE *fptr;
fptr = fopen(file_name, "r");
if (fptr == NULL) {
/* Handle error */
}
c = getc(fptr);
if (c == EOF) {
/* Handle error */
}
if (fclose(fptr) == EOF) {
/* Handle error */
}
}
#include <stdio.h>
void func(cons... | ## Risk Assessment
Using an expression that has side effects as the stream argument to
getc()
,
putc()
, or
getwc()
can result in
unexpected behavior
and
abnormal program termination
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO41-C
Low
Unlikely
Yes
Yes
P3
L3
Automated Detection
Tool
Version
Check... | SEI CERT C Coding Standard > 2 Rules > Rule 09. Input Output (FIO) |
c | 87,151,938 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151938 | 2 | 9 | FIO42-C | Close files when they are no longer needed | A call to the
fopen()
or
freopen()
function must be matched with a call to
fclose()
before the lifetime of the last pointer that stores the return value of the call has ended or before normal program termination, whichever occurs first.
In general, this rule should also be applied to other functions with open and close... | #include <stdio.h>
int func(const char *filename) {
FILE *f = fopen(filename, "r");
if (NULL == f) {
return -1;
}
/* ... */
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *f = fopen(filename, "w");
if (NULL == f) {
exit(EXIT_FAILURE);
}
/* ... */
exit(EXIT_S... | #include <stdio.h>
int func(const char *filename) {
FILE *f = fopen(filename, "r");
if (NULL == f) {
return -1;
}
/* ... */
if (fclose(f) == EOF) {
return -1;
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *f = fopen(filename, "w");
if (NULL == f) {
/* Han... | ## Risk Assessment
Failing to properly close files may allow an attacker to exhaust system resources and can increase the risk that data written into in-memory file buffers will not be flushed in the event of
abnormal program termination
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO42-C
Medium
Unl... | SEI CERT C Coding Standard > 2 Rules > Rule 09. Input Output (FIO) |
c | 87,152,071 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152071 | 2 | 9 | FIO44-C | Only use values for fsetpos() that are returned from fgetpos() | The C Standard, 7.23.9.3 paragraph 2 [
ISO/IEC 9899:2024
], defines the following behavior for
fsetpos()
:
The
fsetpos
function sets the
mbstate_t
object (if any) and file position indicator for the stream pointed to by
stream
according to the value of the object pointed to by
pos
, which shall be a value obtained from... | #include <stdio.h>
#include <string.h>
int opener(FILE *file) {
int rc;
fpos_t offset;
memset(&offset, 0, sizeof(offset));
if (file == NULL) {
return -1;
}
/* Read in data from file */
rc = fsetpos(file, &offset);
if (rc != 0 ) {
return rc;
}
return 0;
}
## Noncompliant Code Example... | #include <stdio.h>
#include <string.h>
int opener(FILE *file) {
int rc;
fpos_t offset;
if (file == NULL) {
return -1;
}
rc = fgetpos(file, &offset);
if (rc != 0 ) {
return rc;
}
/* Read in data from file */
rc = fsetpos(file, &offset);
if (rc != 0 ) {
return rc;
}
return 0;
}
... | ## Risk Assessment
Misuse of the
fsetpos()
function can position a file position indicator to an unintended location in the file.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO44-C
Medium
Unlikely
No
No
P2
L3
Automated Detection
Tool
Version
Checker
Description
(customization)
Users can add a custom ... | SEI CERT C Coding Standard > 2 Rules > Rule 09. Input Output (FIO) |
c | 87,151,941 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151941 | 2 | 9 | FIO45-C | Avoid TOCTOU race conditions while accessing files | A
TOCTOU
(time-of-check, time-of-use)
race condition is possible when two or more concurrent processes are operating on a shared file system [
Seacord 2013b
]. Typically, the first access is a check to verify some attribute of the file, followed by a call to use the file. An attacker can alter the file between the two ... | #include <stdio.h>
void open_some_file(const char *file) {
FILE *f = fopen(file, "r");
if (NULL != f) {
/* File exists, handle error */
} else {
f = fopen(file, "w");
if (NULL == f) {
/* Handle error */
}
/* Write to file */
if (fclose(f) == EOF) {
/* Handle error */
}
... | #include <stdio.h>
void open_some_file(const char *file) {
FILE *f = fopen(file, "wx");
if (NULL == f) {
/* Handle error */
}
/* Write to file */
if (fclose(f) == EOF) {
/* Handle error */
}
}
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
void open_some_file(const char *file) {
int ... | ## Risk Assessment
TOCTOU
race conditions can result in
unexpected behavior
, including privilege escalation.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO45-C
High
Probable
No
No
P6
L2
Automated Detection
Tool
Version
Checker
Description
IO.RACE
File system race condition
TOCTOU
Implemented
premium... | SEI CERT C Coding Standard > 2 Rules > Rule 09. Input Output (FIO) |
c | 87,151,937 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151937 | 2 | 9 | FIO46-C | Do not access a closed file | Using the value of a pointer to a
FILE
object after the associated file is closed is
undefined behavior
. (See
undefined behavior 153
.) Programs that close the standard streams (especially
stdout
but also
stderr
and
stdin
) must be careful not to use these streams in subsequent function calls, particularly those that ... | #include <stdio.h>
int close_stdout(void) {
if (fclose(stdout) == EOF) {
return -1;
}
printf("stdout successfully closed.\n");
return 0;
}
## Noncompliant Code Example
## In this noncompliant code example, thestdoutstream is used after it is closed:
#FFcccc
c
#include <stdio.h>
int close_stdout(void) {... | #include <stdio.h>
int close_stdout(void) {
if (fclose(stdout) == EOF) {
return -1;
}
fputs("stdout successfully closed.", stderr);
return 0;
}
## Compliant Solution
In this compliant solution,
stdout
is not used again after it is closed. This must remain true for the remainder of the program, or
stdout... | ## Risk Assessment
Using the value of a pointer to a
FILE
object after the associated file is closed is
undefined behavior 153
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO46-C
Medium
Unlikely
No
No
P2
L3
Automated Detection
Tool
Version
Checker
Description
Supported
IO.UAC
Use after close
Compass... | SEI CERT C Coding Standard > 2 Rules > Rule 09. Input Output (FIO) |
c | 87,152,167 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152167 | 2 | 9 | FIO47-C | Use valid format strings | The formatted output functions (
fprintf()
and related functions) convert, format, and print their arguments under control of a
format
string. The C Standard, 7.23.6.1, paragraph 3 [
ISO/IEC 9899:2024
], specifies
The format shall be a multibyte character sequence, beginning and ending in its initial shift state. The f... | #include <stdio.h>
void func(void) {
const char *error_msg = "Resource not available to user.";
int error_type = 3;
/* ... */
printf("Error (type %s): %d\n", error_type, error_msg);
/* ... */
}
## Noncompliant Code Example
Mismatches between arguments and conversion specifications may result in
undefined b... | #include <stdio.h>
void func(void) {
const char *error_msg = "Resource not available to user.";
int error_type = 3;
/* ... */
printf("Error (type %d): %s\n", error_type, error_msg);
/* ... */
}
## Compliant Solution
This compliant solution ensures that the arguments to the
printf()
function match their re... | ## Risk Assessment
Incorrectly specified format strings can result in memory corruption or
abnormal program termination
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO47-C
High
Unlikely
Yes
No
P6
L2
Automated Detection
Tool
Version
Checker
Description
format-string-excessive-arguments
format-string-... | SEI CERT C Coding Standard > 2 Rules > Rule 09. Input Output (FIO) |
c | 87,152,310 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152310 | 3 | 5 | FLP00-C | Understand the limitations of floating-point numbers | The C programming language provides the ability to use floating-point numbers for calculations. The C Standard specifies requirements on a
conforming
implementation
for floating-point numbers but makes few guarantees about the specific underlying floating-point representation because of the existence of competing float... | null | null | ## Risk Assessment
Failing to understand the limitations of floating-point numbers can result in unexpected computational results and exceptional conditions, possibly resulting in a violation of data integrity.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FLP00-C
Medium
Probable
No
No
P4
L3
A... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 05. Floating Point (FLP) |
c | 87,152,462 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152462 | 3 | 5 | FLP01-C | Take care in rearranging floating-point expressions | Be careful when rearranging floating-point expressions to ensure the greatest accuracy of the result.
Subclause 5.1.2.3, paragraph 14, of the C Standard [
ISO/IEC 9899:2011
], states:
Rearrangement for floating-point expressions is often restricted because of limitations in precision as well as range. The
implementatio... | null | null | ## Risk Assessment
Failure to understand the limitations in precision of floating-point-represented numbers and their implications on the arrangement of expressions can cause unexpected arithmetic results.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FLP01-C
Low
Probable
No
No
P2
L3
Automated... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 05. Floating Point (FLP) |
c | 87,152,394 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152394 | 3 | 5 | FLP02-C | Avoid using floating-point numbers when precise computation is needed | Computers can represent only a finite number of digits. It is therefore impossible to precisely represent repeating binary-representation values such as 1/3 or 1/5 with the most common floating-point representation: binary floating point.
When precise computation is necessary, use alternative representations that can a... | #include <stdio.h>
/* Returns the mean value of the array */
float mean(float array[], int size) {
float total = 0.0;
size_t i;
for (i = 0; i < size; i++) {
total += array[i];
printf("array[%zu] = %f and total is %f\n", i, array[i], total);
}
if (size != 0)
return total / size;
else
return ... | #include <stdio.h>
/* Returns the mean value of the array */
float mean(int array[], int size) {
int total = 0;
size_t i;
for (i = 0; i < size; i++) {
total += array[i];
printf("array[%zu] = %f and total is %f\n", i, array[i] / 100.0, total / 100.0);
}
if (size != 0)
return ((float) total) / size... | ## Risk Assessment
Using a representation other than floating point may allow for more accurate results.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FLP02-C
Low
Probable
No
No
P2
L3
Automated Detection
Checks for floating
Tool
Version
Checker
Description
float-comparison
Partially checked
Ce... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 05. Floating Point (FLP) |
c | 87,152,060 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152060 | 3 | 5 | FLP03-C | Detect and handle floating-point errors | Errors during floating-point operations are often neglected by programmers who instead focus on validating operands before an operation. Errors that occur during floating-point operations are admittedly difficult to determine and diagnose, but the benefits of doing so often outweigh the costs. This recommendation sugge... | void fpOper_noErrorChecking(void) {
/* ... */
double a = 1e-40, b, c = 0.1;
float x = 0, y;
/* Inexact and underflows */
y = a;
/* Divide-by-zero operation */
b = y / x;
/* Inexact (loss of precision) */
c = sin(30) * a;
/* ... */
}
## Noncompliant Code Example
In this noncompliant code example, fl... | #include <fenv.h>
#pragma STDC FENV_ACCESS ON
void fpOper_fenv(void) {
double a = 1e-40, b, c = 0.1;
float x = 0, y;
int fpeRaised;
/* ... */
feclearexcept(FE_ALL_EXCEPT);
/* Store a into y is inexact and underflows: */
y = a;
fpeRaised = fetestexcept(FE_ALL_EXCEPT);
/* fpeRaised has FE_INEXACT and ... | ## Risk Assessment
Undetected floating-point errors may result in lower program efficiency, inaccurate results, or software
vulnerabilities
. Most processors stall for a significant duration when an operation incurs a NaN (not a number) value.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FLP0... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 05. Floating Point (FLP) |
c | 87,152,304 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152304 | 3 | 5 | FLP04-C | Check floating-point inputs for exceptional values | Floating-point numbers can take on two classes of exceptional values; infinity and NaN (not-a-number). These values are returned as the result of exceptional or otherwise unresolvable floating-point operations. (See also
.) Additionally, they can be directly input by a user by
scanf
or similar functions. Failure to det... | float currentBalance; /* User's cash balance */
void doDeposit() {
float val;
scanf("%f", &val);
if(val >= MAX_VALUE - currentBalance) {
/* Handle range error */
}
currentBalance += val;
}
#include <stdio.h>
int main(int argc, char *argv[]) {
float val, currentBalance=0;
scanf("%f", &val);
curr... | float currentBalance; /* User's cash balance */
void doDeposit() {
float val;
scanf("%f", &val);
if (isinf(val)) {
/* Handle infinity error */
}
if (isnan(val)) {
/* Handle NaN error */
}
if (val >= MAX_VALUE - currentBalance) {
/* Handle range error */
}
currentBalance += val;
}
## Co... | ## Risk Assessment
Inappropriate floating-point inputs can result in invalid calculations and unexpected results, possibly leading to crashing and providing a
denial-of-service
opportunity.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FLP04-C
Low
Probable
No
Yes
P4
L3
Automated Detection
Tool... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 05. Floating Point (FLP) |
c | 87,152,252 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152252 | 3 | 5 | FLP05-C | Do not use denormalized numbers | Most implementations of C use the IEEE 754 standard for floating-point representation. In this representation, floats are encoded using 1 sign bit, 8 exponent bits, and 23 mantissa bits. Doubles are encoded and used exactly the same way, except they use 1 sign bit, 11 exponent bits, and 52 mantissa bits. These bits enc... | #include <stdio.h>
float x = 1/3.0;
printf("Original : %e\n", x);
x = x * 7e-45;
printf("Denormalized: %e\n", x);
x = x / 7e-45;
printf("Restored : %e\n", x);
Original : 3.333333e-01
Denormalized: 2.802597e-45
Restored : 4.003710e-01
## Noncompliant Code Example
This code attempts to reduce a floating-poi... | #include <stdio.h>
double x = 1/3.0;
printf("Original : %e\n", x);
x = x * 7e-45;
printf("Denormalized: %e\n", x);
x = x / 7e-45;
printf("Restored : %e\n", x);
Original : 3.333333e-01
Denormalized: 2.333333e-45
Restored : 3.333333e-01
#include<stdio.h>
float x = 0x1p-125;
double y = 0x1p-1020;
printf("no... | ## Risk Assessment
Floating-point numbers are an approximation; using subnormal floating-point number are a worse approximation.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FLP05-C
Low
Probable
No
No
P2
L3
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the v... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 05. Floating Point (FLP) |
c | 87,152,079 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152079 | 3 | 5 | FLP06-C | Convert integers to floating point for floating-point operations | Using integer arithmetic to calculate a value for assignment to a floating-point variable may lead to loss of information. This problem can be avoided by converting one of the integers in the expression to a floating type.
When converting integers to floating-point values, and vice versa, it is important to carry out p... | void func(void) {
short a = 533;
int b = 6789;
long c = 466438237;
float d = a / 7; /* d is 76.0 */
double e = b / 30; /* e is 226.0 */
double f = c * 789; /* f may be negative due to overflow */
}
## Noncompliant Code Example
In this noncompliant code example, the division and multiplication operations t... | void func(void) {
short a = 533;
int b = 6789;
long c = 466438237;
float d = a / 7.0f; /* d is 76.14286 */
double e = b / 30.; /* e is 226.3 */
double f = (double)c * 789; /* f is 368019768993.0 */
}
void func(void) {
short a = 533;
int b = 6789;
long c = 466438237;
float d = a;
double e = b;
... | ## Risk Assessment
Improper conversions between integers and floating-point values may yield unexpected results, especially loss of precision. Additionally, these unexpected results may actually involve overflow, or undefined behavior.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
FLP06-C
Low
... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 05. Floating Point (FLP) |
c | 87,152,302 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152302 | 3 | 5 | FLP07-C | Cast the return value of a function that returns a floating-point type | Cast the return value of a function that returns a floating point type to ensure predictable program execution.
Subclause 6.8.6.4, paragraph 3, of the C Standard [
ISO/IEC 9899:2011
] states:
If a return statement with an expression is executed, the value of the expression is returned to the caller as the value of the ... | float calc_percentage(float value) {
return value * 0.1f;
}
void float_routine(void) {
float value = 99.0f;
long double percentage;
percentage = calc_percentage(value);
}
## Noncompliant Code Example
This noncompliant code example fails to cast the result of the expression in the return statement and thereby... | float calc_percentage(float value) {
return (float)(value * 0.1f);
}
void float_routine(void) {
float value = 99.0f;
long double percentage;
percentage = calc_percentage(value);
}
void float_routine(void) {
float value = 99.0f;
long double percentage;
percentage = (float) calc_percentage(value);
}
##... | ## Risk Assessment
Failure to follow this guideline can lead to inconsistent results across different platforms.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FLP07-C
Low
Probable
No
Yes
P4
L3
Automated Detection
Tool
Version
Checker
Description
CertC-FLP07
CERT.RTN.FLT.CAST.DBL
CERT.RTN.FLT.IMPLICIT.CA... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 05. Floating Point (FLP) |
c | 87,152,157 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152157 | 2 | 5 | FLP30-C | Do not use floating-point variables as loop counters | Because floating-point numbers represent real numbers, it is often mistakenly assumed that they can represent any simple fraction exactly. Floating-point numbers are subject to representational limitations just as integers are, and binary floating-point numbers cannot represent all real numbers exactly, even if they ca... | void func(void) {
for (float x = 0.1f; x <= 1.0f; x += 0.1f) {
/* Loop may iterate 9 or 10 times */
}
}
void func(void) {
for (float x = 100000001.0f; x <= 100000010.0f; x += 1.0f) {
/* Loop may not terminate */
}
}
## Noncompliant Code Example
In this noncompliant code example, a floating-point varia... | #include <stddef.h>
void func(void) {
for (size_t count = 1; count <= 10; ++count) {
float x = count / 10.0f;
/* Loop iterates exactly 10 times */
}
}
void func(void) {
for (size_t count = 1; count <= 10; ++count) {
float x = 100000000.0f + (count * 1.0f);
/* Loop iterates exactly 10 times */
... | ## Risk Assessment
The use of floating-point variables as loop counters can result in
unexpected behavior
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FLP30-C
Low
Probable
Yes
Yes
P6
L2
Automated Detection
Tool
Version
Checker
Description
for-loop-float
Fully checked
CertC-FLP30
Fully implemented
cer... | SEI CERT C Coding Standard > 2 Rules > Rule 05. Floating Point (FLP) |
c | 87,152,396 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152396 | 2 | 5 | FLP32-C | Prevent or detect domain and range errors in math functions | The C Standard, 7.12.1 [
ISO/IEC 9899:2024
], defines three types of errors that relate specifically to math functions in
<math.h>
. Paragraph 2 states
A domain error
occurs if an input argument is outside the domain over which the mathematical function is defined.
Paragraph 3 states
A
pole error
(also known as a sing... | #include <math.h>
void func(double x) {
double result;
result = sqrt(x);
}
#include <math.h>
void func(double x) {
double result;
result = sinh(x);
}
#include <math.h>
void func(double x, double y) {
double result;
result = pow(x, y);
}
#include <math.h>
void func(float x) {
float result = asin... | #include <math.h>
void func(double x) {
double result;
if (isless(x, 0.0)) {
/* Handle domain error */
}
result = sqrt(x);
}
#include <math.h>
#include <fenv.h>
#include <errno.h>
void func(double x) {
double result;
{
#pragma STDC FENV_ACCESS ON
if (math_errhandling & MATH_ERREXCEPT) {
... | ## Risk Assessment
Failure to prevent or detect domain and range errors in math functions may cause unexpected results.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FLP32-C
Medium
Probable
Yes
Yes
P12
L1
Automated Detection
Tool
Version
Checker
Description
stdlib-limits
Partially checked
Axivion Bauhau... | SEI CERT C Coding Standard > 2 Rules > Rule 05. Floating Point (FLP) |
c | 87,152,068 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152068 | 2 | 5 | FLP34-C | Ensure that floating-point conversions are within range of the new type | If a floating-point value is to be converted to a floating-point value of a smaller range and precision or to an integer type, or if an integer type is to be converted to a floating-point type, the value must be representable in the destination type.
The C Standard, 6.3.1.4, paragraph 2 [
ISO/IEC 9899:2024
], says,
Whe... | void func(float f_a) {
int i_a;
/* Undefined if the integral part of f_a cannot be represented. */
i_a = f_a;
}
void func(double d_a, long double big_d) {
double d_b = (float)big_d;
float f_a = (float)d_a;
float f_b = (float)big_d;
}
## Noncompliant Code Example (floattoint)
This noncompliant code examp... | #include <float.h>
#include <limits.h>
#include <math.h>
#include <stddef.h>
#include <stdint.h>
extern size_t popcount(uintmax_t); /* See INT35-C */
#define PRECISION(umax_value) popcount(umax_value)
void func(float f_a) {
int i_a;
if (isnan(f_a) ||
PRECISION(INT_MAX) < log2f(fabsf(f_a)) ||
(f_a ... | ## Risk Assessment
Converting a floating-point value to a floating-point value of a smaller range and precision or to an integer type, or converting an integer type to a floating-point type, can result in a value that is not representable in the destination type and is undefined behavior on implementations that do not ... | SEI CERT C Coding Standard > 2 Rules > Rule 05. Floating Point (FLP) |
c | 87,152,221 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152221 | 2 | 5 | FLP36-C | Preserve precision when converting integral values to floating-point type | Narrower arithmetic types can be cast to wider types without any effect on the magnitude of numeric values. However, whereas integer types represent exact values, floating-point types have limited precision. The C Standard, 6.3.1.4 paragraph 3 [
ISO/IEC 9899:2024
], states
When a value of integer type is converted to a... | #include <stdio.h>
int main(void) {
long int big = 1234567890L;
float approx = big;
printf("%ld\n", (big - (long int)approx));
return 0;
}
## Noncompliant Code Example
In this noncompliant example, a large value of type
long int
is converted to a value of type
float
without ensuring it is representable in the... | #include <assert.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
extern size_t popcount(uintmax_t); /* See INT35-C */
#define PRECISION(umax_value) popcount(umax_value)
int main(void) {
assert(PRECISION(LONG_MAX) <= DBL_MANT_DIG * log2(FLT_RADIX));
long int big ... | ## Risk Assessment
Conversion from integral types to floating-point types without sufficient precision can lead to loss of precision (loss of least significant bits).
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FLP36-C
Low
Unlikely
Yes
No
P2
L3
Automated Detection
Tool
Version
Checker
Description
impr... | SEI CERT C Coding Standard > 2 Rules > Rule 05. Floating Point (FLP) |
c | 87,152,017 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152017 | 2 | 5 | FLP37-C | Do not use object representations to compare floating-point values | The object representation for floating-point values is implementation defined. However, an implementation that defines the
__STDC_IEC_559__
macro shall conform to the
IEC 60559 floating-point standard and uses what is frequently referred to as
IEEE 754 floating-point arithmetic
[
ISO/IEC 9899:2024
]
. The floating-poin... | #include <stdbool.h>
#include <string.h>
struct S {
int i;
float f;
};
bool are_equal(const struct S *s1, const struct S *s2) {
if (!s1 && !s2)
return true;
else if (!s1 || !s2)
return false;
return 0 == memcmp(s1, s2, sizeof(struct S));
}
## Noncompliant Code Example
In this noncompliant code ex... | #include <stdbool.h>
#include <string.h>
struct S {
int i;
float f;
};
bool are_equal(const struct S *s1, const struct S *s2) {
if (!s1 && !s2)
return true;
else if (!s1 || !s2)
return false;
return s1->i == s2->i &&
s1->f == s2->f;
}
## Compliant Solution
## In this compliant solution, ... | ## Risk Assessment
Using the object representation of a floating-point value for comparisons can lead to incorrect equality results, which can lead to unexpected behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FLP37-C
Low
Unlikely
Yes
Yes
P3
L3
Automated Detection
Tool
Version
Checker
Descriptio... | SEI CERT C Coding Standard > 2 Rules > Rule 05. Floating Point (FLP) |
c | 87,152,417 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152417 | 3 | 4 | INT00-C | Understand the data model used by your implementation(s) | A
data model
defines the sizes assigned to standard data types. It is important to understand the data models used by your
implementation
. However, if your code depends on any assumptions not guaranteed by the standard, you should provide static assertions to ensure that your assumptions are valid. (See
.) Assumptions... | int f(void) {
FILE *fp;
int x;
/* ... */
if (fscanf(fp, "%ld", &x) < 1) {
return -1; /* Indicate failure */
}
/* ... */
return 0;
}
unsigned int a, b;
unsigned long c;
/* Initialize a and b */
c = (unsigned long)a * b; /* Not guaranteed to fit */
## Noncompliant Code Example
This noncompliant example a... | int f(void) {
FILE *fp;
int x;
/* Initialize fp */
if (fscanf(fp, "%d", &x) < 1) {
return -1; /* Indicate failure */
}
/* ... */
return 0;
}
#if UINT_MAX > UINTMAX_MAX/UINT_MAX
#error No safe type is available.
#endif
/* ... */
unsigned int a, b;
uintmax_t c;
/* Initialize a and b */
c = (uintmax_t)a * ... | ## Risk Assessment
Understanding the data model used by your
implementation
is necessary to avoid making errors about the sizes of integer types and the range of values they can represent. Making assumptions about the sizes of data types may lead to buffer-overflow-style attacks.
Recommendation
Severity
Likelihood
Dete... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,208 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152208 | 3 | 4 | INT01-C | Use size_t or rsize_t for all integer values representing the size of an object | The
size_t
type is the unsigned integer type of the result of the
sizeof
operator. Variables of type
size_t
are guaranteed to be of sufficient precision to represent the size of an object. The limit of
size_t
is specified by the
SIZE_MAX
macro.
The type
size_t
generally covers the entire address space. The C Standard, ... | char *copy(size_t n, const char *c_str) {
int i;
char *p;
if (n == 0) {
/* Handle unreasonable object size error */
}
p = (char *)malloc(n);
if (p == NULL) {
return NULL; /* Indicate malloc failure */
}
for ( i = 0; i < n; ++i ) {
p[i] = *c_str++;
}
return p;
}
/* ... */
char c_str[] ... | char *copy(rsize_t n, const char *c_str) {
rsize_t i;
char *p;
if (n == 0 || n > RSIZE_MAX) {
/* Handle unreasonable object size error */
}
p = (char *)malloc(n);
if (p == NULL) {
return NULL; /* Indicate malloc failure */
}
for (i = 0; i < n; ++i) {
p[i] = *c_str++;
}
return p;
}
/* ... | ## Risk Assessment
The improper calculation or manipulation of an object's size can result in exploitable
vulnerabilities
.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT01-C
Medium
Probable
No
Yes
P8
L2
Automated Detection
Tool
Version
Checker
Description
CertC-INT01
LANG.TYPE.BASIC
Basic ... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,206 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152206 | 3 | 4 | INT02-C | Understand integer conversion rules | Conversions can occur explicitly as the result of a cast or implicitly as required by an operation. Although conversions are generally required for the correct execution of a program, they can also lead to lost or misinterpreted data. Conversion of an operand value to a compatible type causes no change to the value or ... | int si = -1;
unsigned int ui = 1;
printf("%d\n", si < ui);
uint8_t port = 0x5a;
uint8_t result_8 = ( ~port ) >> 4;
#include <limits.h>
unsigned char max = CHAR_MAX + 1;
for (char i = 0; i < max; ++i) {
printf("i=0x%08x max=0x%08x\n", i, max);
}
unsigned short x = 45000, y = 50000;
unsigned int z = x * y;
## Nonc... | int si = -1;
unsigned ui = 1;
printf("%d\n", si < (int)ui);
int si = /* Some signed value */;
unsigned ui = /* Some unsigned value */;
printf("%d\n", (si < 0 || (unsigned)si < ui));
uint8_t port = 0x5a;
uint8_t result_8 = (uint8_t) (~port) >> 4;
#include <limits.h>
unsigned char max = CHAR_MAX + 1;
for (unsigned ch... | ## Risk Assessment
Misunderstanding integer conversion rules can lead to errors, which in turn can lead to exploitable
vulnerabilities
. The major risks occur when narrowing the type (which requires a specific cast or assignment), converting from unsigned to signed, or converting from negative to unsigned.
Recommendati... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,245 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152245 | 3 | 4 | INT04-C | Enforce limits on integer values originating from tainted sources | All integer values originating from
tainted sources
should be evaluated to determine if they have identifiable upper and lower bounds. If so, these limits should be enforced by the interface. Restricting the input of excessively large or small integers helps prevent overflow, truncation, and other type range errors. Fu... | char** create_table(void) {
const char* const lenstr = getenv("TABLE_SIZE");
const size_t length = lenstr ? strtoul(lenstr, NULL, 10) : 0;
if (length > SIZE_MAX / sizeof(char *))
return NULL; /* Indicate error to caller */
const size_t table_size = length * sizeof(char *);
char** const table = (char *... | enum { MAX_TABLE_LENGTH = 256 };
char** create_table(void) {
const char* const lenstr = getenv("TABLE_SIZE");
const size_t length = lenstr ? strtoul(lenstr, NULL, 10) : 0;
if (length == 0 || length > MAX_TABLE_LENGTH)
return NULL; /* Indicate error to caller */
const size_t table_size = length * sizeof... | null | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,392 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152392 | 3 | 4 | INT05-C | Do not use input functions to convert character data if they cannot handle all possible inputs | Do not use functions that input characters and convert them to integers if the functions cannot handle all possible inputs. For example, formatted input functions such as
scanf()
,
fscanf()
,
vscanf()
, and
vfscanf()
can be used to read string data from
stdin
or (in the cases of
fscanf()
and
vfscanf()
) other input str... | long num_long;
if (scanf("%ld", &num_long) != 1) {
/* Handle error */
}
## Noncompliant Code Example
This noncompliant code example uses the
scanf()
function to read a string from
stdin
and convert it to a
long
. The
scanf()
and
fscanf()
functions have
undefined behavior
if the value of the result of this operation... | long num_long;
errno = 0;
if (scanf("%ld", &num_long) != 1) {
/* Handle error */
}
else if (ERANGE == errno) {
if (puts("number out of range\n") == EOF) {
/* Handle error */
}
}
char buff[25];
char *end_ptr;
long num_long;
if (fgets(buff, sizeof(buff), stdin) == NULL) {
if (puts("EOF or read error\n") ... | ## Risk Assessment
Although it is relatively rare for a violation of this recommendation to result in a security
vulnerability
, it can easily result in lost or misinterpreted data.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT05-C
Medium
Probable
Yes
No
P8
L2
Automated Detection
Tool
Vers... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,386 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152386 | 3 | 4 | INT07-C | Use only explicitly signed or unsigned char type for numeric values | The three types
char
,
signed char
, and
unsigned char
are collectively called the
character types
. Compilers have the latitude to define
char
to have the same range, representation, and behavior as
either
signed char
or
unsigned char
. Irrespective of the choice made,
char
is a separate type from the other two and is... | char c = 200;
int i = 1000;
printf("i/c = %d\n", i/c);
## Noncompliant Code Example
In this noncompliant code example, the
char
-type variable
c
may be signed or unsigned. Assuming 8-bit, two's complement character types, this code may print out either
i/c = 5
(unsigned) or
i/c = -17
(signed). It is much more difficul... | unsigned char c = 200;
int i = 1000;
printf("i/c = %d\n", i/c);
## Compliant Solution
In this compliant solution, the variable
c
is declared as
unsigned char
. The subsequent division operation is now independent of the signedness of
char
and consequently has a predictable result.
#ccccff
c
unsigned char c = 200;
int ... | ## Risk Assessment
This is a subtle error that results in a disturbingly broad range of potentially severe
vulnerabilities
. At the very least, this error can lead to unexpected numerical results on different platforms. Unexpected arithmetic values when applied to arrays or pointers can yield buffer overflows or other ... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,450 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152450 | 3 | 4 | INT08-C | Verify that all integer values are in range | Integer operations must result in an integer value within the range of the integer type (that is, the resulting value is the same as the result produced by unlimited-range integers). Frequently, the range is more restrictive depending on the use of the integer value, for example, as an index. Integer values can be veri... | int i = /* Expression that evaluates to the value 32767 */;
/* ... */
if (i + 1 <= i) {
/* Handle overflow */
}
/* Expression involving i + 1 */
## Noncompliant Code Example
In this noncompliant example,
i + 1
will overflow on a 16-bit machine. The C Standard allows signed integers to overflow and produce incorrect ... | long i = /* Expression that evaluates to the value 32767 */;
/* ... */
/* No test is necessary; i is known not to overflow */
/* Expression involving i + 1 */
## Compliant Solution
Using a
long
instead of an
int
is guaranteed to accommodate the computed value:
#ccccff
c
long i = /* Expression that evaluates to the val... | ## Risk Assessment
Out-of-range integer values can result in reading from or writing to arbitrary memory locations and the execution of arbitrary code.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT08-C
Medium
Probable
No
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
integer... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,467 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152467 | 3 | 4 | INT09-C | Ensure enumeration constants map to unique values | A C enumeration defines a type with a finite set of values represented by identifiers known as
enumeration constants
, or enumerators. An enumerator is a constant integer expression whose value is representable as an
int
. Although the language allows multiple enumerators of the same type to have the same value, it is ... | enum Color { red=4, orange, yellow, green, blue, indigo=6, violet };
const char* color_name(enum Color col) {
switch (col) {
case red: return "red";
case orange: return "orange";
case yellow: return "yellow";
case green: return "green";
case blue: return "blue";
case indigo: return "indigo"; /* Error: ... | enum Color { red, orange, yellow, green, blue, indigo, violet };
enum Color { red=4, orange, yellow, green, blue, indigo, violet };
enum Color {
red=4,
orange=5,
yellow=6,
green=7,
blue=8,
indigo=6,
violet=7
};
## Compliant Solution
To prevent the error discussed of the noncompliant code example,... | ## Risk Assessment
Failing to ensure that constants within an enumeration have unique values can result in unexpected results.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT09-C
Low
Probable
Yes
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
enum-implicit-value
Fully checked
... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,120 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152120 | 3 | 4 | INT10-C | Do not assume a positive remainder when using the % operator | In C89 (and historical K&R
implementations
), the meaning of the remainder operator for negative operands was
implementation-defined
. This behavior was changed in C99, and the change remains in C11.
Because not all C compilers are strictly C-conforming, programmers cannot rely on the behavior of the
%
operator if they... | int insert(int index, int *list, int size, int value) {
if (size != 0) {
index = (index + 1) % size;
list[index] = value;
return index;
}
else {
return -1;
}
}
int insert(int index, int *list, int size, int value) {
if (size != 0) {
index = abs((index + 1) % size);
list[index] = value... | int insert(size_t* result, size_t index, int *list, size_t size, int value) {
if (size != 0 && size != SIZE_MAX) {
index = (index + 1) % size;
list[index] = value;
*result = index;
return 1;
}
else {
return 0;
}
}
## Compliant Solution (Unsigned Types)
The most appropriate solution in this ... | ## Risk Assessment
Incorrectly assuming that the result of the remainder operator for signed operands will always be positive can lead to an out-of-bounds memory accessor other flawed logic.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT10-C
High
Unlikely
No
No
P3
L3
Automated Detection
Too... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,212 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152212 | 3 | 4 | INT12-C | Do not make assumptions about the type of a plain int bit-field when used in an expression | Bit-fields can be used to allow flags or other integer values with small ranges to be packed together to save storage space.
It is
implementation-defined
whether the specifier
int
designates the same type as
signed int
or the same type as
unsigned int
for bit-fields. According to the C Standard [
ISO/IEC 9899:2011
], C... | struct {
int a: 8;
} bits = {255};
int main(void) {
printf("bits.a = %d.\n", bits.a);
return 0;
}
## Noncompliant Code Example
This noncompliant code depends on
implementation-defined behavior
. It prints either
-1
or
255
, depending on whether a plain
int
bit-field is signed or unsigned.
#FFcccc
c
struct {
int... | struct {
unsigned int a: 8;
} bits = {255};
int main(void) {
printf("bits.a = %d.\n", bits.a);
return 0;
}
## Compliant Solution
## This compliant solution uses anunsigned intbit-field and does not depend on implementation-defined behavior:
#ccccff
c
struct {
unsigned int a: 8;
} bits = {255};
int main(void) {
... | ## Risk Assessment
Making invalid assumptions about the type of a bit-field or its layout can result in unexpected program flow.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT12-C
Low
Unlikely
No
No
P1
L3
Automated Detection
Tool
Version
Checker
Description
bitfield-type
Fully checked
CertC... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,374 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152374 | 3 | 4 | INT13-C | Use bitwise operators only on unsigned operands | Bitwise operators include the complement operator
~
, bitwise shift operators
>>
and
<<
, bitwise AND operator
&
, bitwise exclusive OR operator
^
, bitwise inclusive OR operator
|
and compound assignment operators >>=, <<=, &=, ^= and |=. Bitwise operators should be used only with unsigned integer operands, as the res... | int rc = 0;
int stringify = 0x80000000;
char buf[sizeof("256")];
rc = snprintf(buf, sizeof(buf), "%u", stringify >> 24);
if (rc == -1 || rc >= sizeof(buf)) {
/* Handle error */
}
## Noncompliant Code Example (Right Shift)
The right-shift operation may be implemented as either an arithmetic (signed) shift or a logica... | int rc = 0;
unsigned int stringify = 0x80000000;
char buf[sizeof("256")];
rc = snprintf(buf, sizeof(buf), "%u", stringify >> 24);
if (rc == -1 || rc >= sizeof(buf)) {
/* Handle error */
}
## Compliant Solution (Right Shift)
In this compliant solution,
stringify
is declared as an
unsigned
integer. The value of the re... | ## Risk Assessment
Performing bitwise operations on signed numbers can lead to buffer overflows and the execution of arbitrary code by an attacker in some cases, unexpected or implementation-defined behavior in others.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT13-C
High
Unlikely
Yes
No
... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,075 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152075 | 3 | 4 | INT14-C | Avoid performing bitwise and arithmetic operations on the same data | Avoid performing bitwise and arithmetic operations on the same data. In particular, bitwise operations are frequently performed on arithmetic values as a form of premature optimization. Bitwise operators include the unary operator
~
and the binary operators
<<
,
>>
,
&
,
^
, and
|
. Although such operations are valid a... | int compute(int x) {
int y = x << 2;
x += y + 1;
return x;
}
// ...
int x = compute(50);
int compute(int x) {
x >>= 2;
return x;
}
// ...
int x = compute(-50);
## Noncompliant Code Example (Left Shift)
In this noncompliant code example, both bit manipulation and arithmetic manipulation are performed on ... | int compute(int x) {
return 5 * x + 1;
}
// ...
int x = compute(50);
int compute(int x) {
return x / 4;
}
// ...
int x = compute(-50);
## Compliant Solution (Left Shift)
In this compliant solution, the assignment statement is modified to reflect the arithmetic nature of
x
, resulting in a clearer indication o... | ## Risk Assessment
Performing bit manipulation and arithmetic operations on the same variable obscures the programmer's intentions and reduces readability. It also makes it more difficult for a security auditor or maintainer to determine which checks must be performed to eliminate
security flaws
and ensure data integri... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,366 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152366 | 3 | 4 | INT15-C | Use intmax_t or uintmax_t for formatted IO on programmer-defined integer types | Few programmers consider the issues around formatted I/O and type definitions. A programmer-defined integer type might be any type supported by the
implementation
, even a type larger than
unsigned long long
. For example, given an implementation that supports 128-bit unsigned integers and provides a
uint_fast128_t
typ... | #include <stdio.h>
mytypedef_t x;
/* ... */
printf("%llu", (unsigned long long) x);
#include <stdio.h>
mytypedef_t x;
/* ... */
if (scanf("%llu", &x) != 1) {
/* Handle error */
}
## Noncompliant Code Example (printf())
This noncompliant code example prints the value of
x
as an
unsigned long long
value even tho... | #include <stdio.h>
#include <inttypes.h>
mytypedef_t x;
/* ... */
printf("%ju", (uintmax_t) x);
#include <stdio.h>
#include <inttypes.h>
mytypedef_t x;
/* ... */
#ifdef _MSC_VER
printf("%llu", (uintmax_t) x);
#else
printf("%ju", (uintmax_t) x);
#endif
#include <stdio.h>
#include <inttypes.h>
#include <err... | ## Risk Assessment
Failure to use an appropriate conversion specifier when inputting or outputting programmer-defined integer types can result in buffer overflow and lost or misinterpreted data.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT15-C
High
Unlikely
No
Yes
P6
L2
Automated Detectio... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,334 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152334 | 3 | 4 | INT16-C | Do not make assumptions about representation of signed integers | Although many common implementations use a two's complement representation of signed integers, the C Standard declares such use as
implementation-defined
and allows all of the following representations:
Sign and magnitude
Two's complement
One's complement
This is a specific example of
. | int value;
if (scanf("%d", &value) == 1) {
if (value & 0x1 != 0) {
/* Take action if value is odd */
}
}
## Noncompliant Code Example
One way to check whether a number is even or odd is to examine the least significant bit, but the results will be inconsistent. Specifically, this example gives unexpected beha... | int value;
if (scanf("%d", &value) == 1) {
if (value % 2 != 0) {
/* Take action if value is odd */
}
}
unsigned int value;
if (scanf("%u", &value) == 1) {
if (value & 0x1 != 0) {
/* Take action if value is odd */
}
}
## Compliant Solution
The same thing can be achieved compliantly using the modulo o... | ## Risk Assessment
Incorrect assumptions about integer representation can lead to execution of unintended code branches and other unexpected behavior.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT16-C
Medium
Unlikely
No
No
P2
L3
Automated Detection
Tool
Version
Checker
Description
bitop-ty... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,319 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152319 | 3 | 4 | INT17-C | Define integer constants in an implementation-independent manner | Integer constants are often used as masks or specific bit values. Frequently, these constants are expressed in hexadecimal form to indicate to the programmer how the data might be represented in the machine. However, hexadecimal integer constants are frequently used in a nonportable manner. | /* (Incorrect) Set all bits in mask to 1 */
const unsigned long mask = 0xFFFFFFFF;
unsigned long flipbits(unsigned long x) {
return x ^ mask;
}
const unsigned long mask = 0x80000000;
unsigned long x;
/* Initialize x */
x |= mask;
## Noncompliant Code Example
In this pedagogical noncompliant code example, the
fli... | /* (Correct) Set all bits in mask to 1 */
const unsigned long mask = -1;
unsigned long flipbits(unsigned long x) {
return x ^ mask;
}
const unsigned long mask = ~(ULONG_MAX >> 1);
unsigned long x;
/* Initialize x */
x |= mask;
## Compliant Solution (−1)
In this compliant solution, the integer constant
-1
is used... | ## Risk Assessment
Vulnerabilities
are frequently introduced while porting code. A buffer overflow vulnerability may result, for example, if an incorrectly defined integer constant is used to determine the size of a buffer. It is always best to write portable code, especially when there is no performance overhead for d... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,419 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152419 | 3 | 4 | INT18-C | Evaluate integer expressions in a larger size before comparing or assigning to that size | If an integer expression involving an operation is compared to or assigned to a larger integer size, that integer expression should be evaluated in that larger size by explicitly casting one of the operands. | #include <stdlib.h>
#include <stdint.h> /* For SIZE_MAX */
enum { BLOCK_HEADER_SIZE = 16 };
void *AllocateBlock(size_t length) {
struct memBlock *mBlock;
if (length + BLOCK_HEADER_SIZE > (unsigned long long)SIZE_MAX)
return NULL;
mBlock = (struct memBlock *)malloc(
length + BLOCK_HEADER_SIZE
);
i... | #include <stdlib.h>
#include <stdint.h>
enum { BLOCK_HEADER_SIZE = 16 };
void *AllocateBlock(size_t length) {
struct memBlock *mBlock;
if ((unsigned long long)length + BLOCK_HEADER_SIZE > SIZE_MAX) {
return NULL;
}
mBlock = (struct memBlock *)malloc(
length + BLOCK_HEADER_SIZE
);
if (!mBlock) {... | ## Risk Assessment
Failure to cast integers before comparing or assigning them to a larger integer size can result in software
vulnerabilities
that can allow the execution of arbitrary code by an attacker with the permissions of the vulnerable process.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT18... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 04. Integers (INT) |
c | 87,152,236 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152236 | 2 | 4 | INT30-C | Ensure that unsigned integer operations do not wrap | The C Standard, 6.2.5, paragraph 11 [
ISO/IEC 9899:2024
], states
A computation involving unsigned operands can never produce an overflow, because arithmetic for the unsigned type is performed modulo
2^
N
.
This behavior is more informally called
unsigned integer wrapping
. Unsigned integer operations can wrap if the r... | null | #include <stdckdint.h>
void func(unsigned int ui_a, unsigned int ui_b) {
unsigned int usum;
if (ckd_add(&usum, ui_a, ui_b)) {
/* Handle error */
}
/* ... */
}
#include <stdckdint.h>
void func(unsigned int ui_a, unsigned int ui_b) {
unsigned int udiff;
if (ckd_sub(&udiff, ui_a, ui_b)) {
/* Handle ... | ## Risk Assessment
Integer wrap can lead to buffer overflows and the execution of arbitrary code by an attacker. Note that this rule is not automatically repairable in contrast to
. This is because integer wrapping is occasionally intended (see
INT30-C-EX1
), and repairing such wrapping would turn correct code into cod... | SEI CERT C Coding Standard > 2 Rules > Rule 04. Integers (INT) |
c | 87,152,211 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152211 | 2 | 4 | INT31-C | Ensure that integer conversions do not result in lost or misinterpreted data | Integer conversions, both implicit and explicit (using a cast), must be guaranteed not to result in lost or misinterpreted data. This rule is particularly true for integer values that originate from untrusted sources and are used in any of the following ways:
Integer operands of any pointer arithmetic, including array ... | #include <limits.h>
void func(void) {
unsigned long int u_a = ULONG_MAX;
signed char sc;
sc = (signed char)u_a; /* Cast eliminates warning */
/* ... */
}
#include <limits.h>
void func(signed int si) {
/* Cast eliminates warning */
unsigned int ui = (unsigned int)si;
/* ... */
}
/* ... */
func(INT_M... | #include <limits.h>
void func(void) {
unsigned long int u_a = ULONG_MAX;
signed char sc;
if (u_a <= SCHAR_MAX) {
sc = (signed char)u_a; /* Cast eliminates warning */
} else {
/* Handle error */
}
}
#include <limits.h>
void func(signed int si) {
unsigned int ui;
if (si < 0) {
/* Handle err... | ## Risk Assessment
Integer truncation errors can lead to buffer overflows and the execution of arbitrary code by an attacker.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT31-C
High
Probable
No
Yes
P12
L1
Automated Detection
Tool
Version
Checker
Description
eof-small-int-comparison
explicit-cast-over... | SEI CERT C Coding Standard > 2 Rules > Rule 04. Integers (INT) |
c | 87,152,210 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152210 | 2 | 4 | INT32-C | Ensure that operations on signed integers do not result in overflow | Signed integer overflow is
undefined behavior 36
. Consequently,
implementations
have considerable latitude in how they deal with signed integer overflow. (See
.) An implementation that defines signed integer types as being modulo, for example, need not detect integer overflow. Implementations may also trap on signed a... | null | #include <limits.h>
void f(signed int si_a, signed int si_b) {
signed int sum;
if (((si_b > 0) && (si_a > (INT_MAX - si_b))) ||
((si_b < 0) && (si_a < (INT_MIN - si_b)))) {
/* Handle error */
} else {
sum = si_a + si_b;
}
/* ... */
}
#include <stdckdint.h>
void f(signed int si_a, signed int ... | ## Risk Assessment
Integer overflow can lead to buffer overflows and the execution of arbitrary code by an attacker.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT32-C
High
Likely
No
Yes
P18
L1
Automated Detection
Tool
Version
Checker
Description
integer-overflow
Fully checked
ALLOC.SIZE.ADDOFLOW
ALL... | SEI CERT C Coding Standard > 2 Rules > Rule 04. Integers (INT) |
c | 87,152,254 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152254 | 2 | 4 | INT33-C | Ensure that division and remainder operations do not result in divide-by-zero errors | The C Standard identifies the following condition under which division and remainder operations result in
undefined behavior (UB)
:
UB
Description
41
The value of the second operand of the
/
or
%
operator is zero (6.5.5).
Ensure that division and remainder operations do not result in divide-by-zero errors.
## Division
... | null | null | ## Risk Assessment
A divide-by-zero error can result in
abnormal program termination
and denial of service.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT33-C
Low
Likely
No
Yes
P6
L2
Automated Detection
Tool
Version
Checker
Description
int-division-by-zero
int-modulo-by-zero
csa-division-by-zero
(C++... | SEI CERT C Coding Standard > 2 Rules > Rule 04. Integers (INT) |
c | 87,152,418 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152418 | 2 | 4 | INT34-C | Do not shift an expression by a negative number of bits or by greater than or equal to the number of bits that exist in the operand | Bitwise shifts include left-shift operations of the form
shift-expression
<<
additive-expression
and right-shift operations of the form
shift-expression
>>
additive-expression
. The standard integer promotions are first performed on the operands, each of which has an integer type. The type of the result is that of the ... | void func(unsigned int ui_a, unsigned int ui_b) {
unsigned int uresult = ui_a << ui_b;
/* ... */
}
#include <limits.h>
#include <stddef.h>
#include <inttypes.h>
void func(signed long si_a, signed long si_b) {
signed long result;
if (si_a > (LONG_MAX >> si_b)) {
/* Handle error */
} else {
result = s... | #include <limits.h>
#include <stddef.h>
#include <inttypes.h>
extern size_t popcount(uintmax_t);
#define PRECISION(x) popcount(x)
void func(unsigned int ui_a, unsigned int ui_b) {
unsigned int uresult = 0;
if (ui_b >= PRECISION(UINT_MAX)) {
/* Handle error */
} else {
uresult = ui_a << ui_b;
}
/* .... | ## Risk Assessment
Although shifting a negative number of bits or shifting a number of bits greater than or equal to the width of the promoted left operand is undefined behavior in C, the risk is generally low because processors frequently reduce the shift amount modulo the width of the type.
Rule
Severity
Likelihood
D... | SEI CERT C Coding Standard > 2 Rules > Rule 04. Integers (INT) |
c | 87,151,939 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151939 | 2 | 4 | INT35-C | Use correct integer precisions | Integer types in C have both a
size
and a
precision
. The size indicates the number of bytes used by an object and can be retrieved for any object or type using the
sizeof
operator. The precision of an integer type is the number of bits it uses to represent values, excluding any sign and padding bits.
Padding bits con... | null | null | null | SEI CERT C Coding Standard > 2 Rules > Rule 04. Integers (INT) |
c | 87,152,081 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152081 | 2 | 4 | INT36-C | Converting a pointer to integer or integer to pointer | Although programmers often use integers and pointers interchangeably in C, pointer-to-integer and integer-to-pointer conversions are
implementation-defined
.
Conversions between integers and pointers can have undesired consequences depending on the
implementation
.
According to the C Standard, subclause 6.3.2.3 [
ISO/I... | void f(void) {
char *ptr;
/* ... */
unsigned int number = (unsigned int)ptr;
/* ... */
}
void func(unsigned int flag) {
char *ptr;
/* ... */
unsigned int number = (unsigned int)ptr;
number = (number & 0x7fffff) | (flag << 23);
ptr = (char *)number;
}
unsigned int *g(void) {
unsigned int *ptr = 0xd... | #include <stdint.h>
void f(void) {
char *ptr;
/* ... */
uintptr_t number = (uintptr_t)ptr;
/* ... */
}
struct ptrflag {
char *pointer;
unsigned int flag : 9;
} ptrflag;
void func(unsigned int flag) {
char *ptr;
/* ... */
ptrflag.pointer = ptr;
ptrflag.flag = flag;
}
## Compliant Solution
Any... | ## Risk Assessment
Converting from pointer to integer or vice versa results in code that is not portable and may create unexpected pointers to invalid memory locations.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
INT36-C
Low
Probable
Yes
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
po... | SEI CERT C Coding Standard > 2 Rules > Rule 04. Integers (INT) |
c | 87,152,150 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152150 | 3 | 8 | MEM00-C | Allocate and free memory in the same module, at the same level of abstraction | Dynamic memory management is a common source of programming flaws that can lead to security
vulnerabilities
. Poor memory management can lead to security issues, such as heap-buffer overflows, dangling pointers, and double-free issues [
Seacord 2013
]. From the programmer's perspective, memory management involves alloc... | enum { MIN_SIZE_ALLOWED = 32 };
int verify_size(char *list, size_t size) {
if (size < MIN_SIZE_ALLOWED) {
/* Handle error condition */
free(list);
return -1;
}
return 0;
}
void process_list(size_t number) {
char *list = (char *)malloc(number);
if (list == NULL) {
/* Handle allocation error *... | enum { MIN_SIZE_ALLOWED = 32 };
int verify_size(const char *list, size_t size) {
if (size < MIN_SIZE_ALLOWED) {
/* Handle error condition */
return -1;
}
return 0;
}
void process_list(size_t number) {
char *list = (char *)malloc(number);
if (list == NULL) {
/* Handle allocation error */
}
... | ## Risk Assessment
The mismanagement of memory can lead to freeing memory multiple times or writing to already freed memory. Both of these coding errors can result in an attacker executing arbitrary code with the permissions of the vulnerable process. Memory management errors can also lead to resource depletion and
den... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 08. Memory Management (MEM) |
c | 87,152,148 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152148 | 3 | 8 | MEM01-C | Store a new value in pointers immediately after free() | Dangling pointers can lead to exploitable double-free and access-freed-memory
vulnerabilities
. A simple yet effective way to eliminate dangling pointers and avoid many memory-related vulnerabilities is to set pointers to
NULL
after they are freed or to set them to another valid object. | char *message;
int message_type;
/* Initialize message and message_type */
if (message_type == value_1) {
/* Process message type 1 */
free(message);
}
/* ...*/
if (message_type == value_2) {
/* Process message type 2 */
free(message);
}
## Noncompliant Code Example
In this noncompliant code example, the ty... | char *message;
int message_type;
/* Initialize message and message_type */
if (message_type == value_1) {
/* Process message type 1 */
free(message);
message = NULL;
}
/* ... */
if (message_type == value_2) {
/* Process message type 2 */
free(message);
message = NULL;
}
## Compliant Solution
Calling
free... | ## Risk Assessment
Setting pointers to
NULL
or to another valid value after memory is freed is a simple and easily implemented solution for reducing dangling pointers. Dangling pointers can result in freeing memory multiple times or in writing to memory that has already been freed. Both of these problems can lead to an... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 08. Memory Management (MEM) |
c | 87,152,375 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152375 | 3 | 8 | MEM02-C | Immediately cast the result of a memory allocation function call into a pointer to the allocated type | An object of type
void *
is a generic data pointer. It can point to any data object. For any incomplete or object type
T
, C permits implicit conversion from
T *
to
void *
or from
void *
to
T *
. C Standard memory allocation functions
aligned_alloc()
,
malloc()
,
calloc()
, and
realloc()
use
void *
to declare paramete... | #include <stdlib.h>
typedef struct gadget gadget;
struct gadget {
int i;
double d;
};
typedef struct widget widget;
struct widget {
char c[10];
int i;
double d;
};
widget *p;
/* ... */
p = malloc(sizeof(gadget)); /* Imminent problem */
if (p != NULL) {
p->i = 0; /* Undefined behavior */... | widget *p;
/* ... */
p = (widget *)malloc(sizeof(widget));
#define MALLOC(type) ((type *)malloc(sizeof(type)))
widget *p;
/* ... */
p = MALLOC(widget); /* OK */
if (p != NULL) {
p->i = 0; /* OK */
p->d = 0.0; /* OK */
}
#define MALLOC_ARRAY(number, type) \
((type *)malloc((number) * s... | ## Risk Assessment
Failing to cast the result of a memory allocation function call into a pointer to the allocated type can result in inadvertent pointer conversions. Code that follows this recommendation will compile and execute equally well in C++.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Lev... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 08. Memory Management (MEM) |
c | 87,152,468 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152468 | 3 | 8 | MEM03-C | Clear sensitive information stored in reusable resources | Sensitive data stored in reusable resources may be inadvertently leaked to a less privileged user or attacker if not properly cleared. Examples of reusable resources include
Dynamically allocated memory
Statically allocated memory
Automatically allocated (stack) memory
Memory caches
Disk
Disk caches
The manner in which... | char *secret;
/* Initialize secret to a null-terminated byte string,
of less than SIZE_MAX chars */
size_t size = strlen(secret);
char *new_secret;
new_secret = (char *)malloc(size+1);
if (!new_secret) {
/* Handle error */
}
strcpy(new_secret, secret);
/* Process new_secret... */
free(new_secret);
new_secret =... | char *secret;
/* Initialize secret to a null-terminated byte string,
of less than SIZE_MAX chars */
size_t size = strlen(secret);
char *new_secret;
/* Use calloc() to zero-out allocated space */
new_secret = (char *)calloc(size+1, sizeof(char));
if (!new_secret) {
/* Handle error */
}
strcpy(new_secret, secret);... | ## Risk Assessment
In practice, this type of
security flaw
can expose sensitive information to unintended parties. The Sun tarball
vulnerability
discussed in
Secure Coding Principles & Practices: Designing and Implementing Secure Applications
[
Graf 2003
] and Sun Security Bulletin #00122 [
Sun 1993
] shows a violation... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 08. Memory Management (MEM) |
c | 87,152,091 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152091 | 3 | 8 | MEM04-C | Beware of zero-length allocations | When the requested size is 0, the behavior of the memory allocation functions
malloc()
,
calloc()
, and
realloc()
is
implementation-defined
. Subclause 7.22.3 of the C Standard [
ISO/IEC 9899:2011
] states:
If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is retu... | size_t size;
/* Initialize size, possibly by user-controlled input */
int *list = (int *)malloc(size);
if (list == NULL) {
/* Handle allocation error */
}
else {
/* Continue processing list */
}
size_t nsize = /* Some value, possibly user supplied */;
char *p2;
char *p = (char *)malloc(100);
if (p == NULL) {
/* ... | size_t size;
/* Initialize size, possibly by user-controlled input */
if (size == 0) {
/* Handle error */
}
int *list = (int *)malloc(size);
if (list == NULL) {
/* Handle allocation error */
}
/* Continue processing list */
size_t nsize;
/* Initialize nsize */
char *p2;
char *p = (char *)malloc(100);
if (p == NU... | ## Risk Assessment
Allocating 0 bytes can lead to
abnormal program termination
.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
MEM04-C
Low
Likely
No
Yes
P6
L2
Automated Detection
Tool
Version
Checker
Description
zero-size-alloc
Fully checked
(customization)
Users can add a custom check for all... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 08. Memory Management (MEM) |
c | 87,152,078 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152078 | 3 | 8 | MEM05-C | Avoid large stack allocations | Avoid excessive stack allocations, particularly in situations where the growth of the stack can be controlled or influenced by an attacker. See
for more information on preventing attacker-controlled integers from exhausting memory. | int copy_file(FILE *src, FILE *dst, size_t bufsize) {
char buf[bufsize];
while (fgets(buf, bufsize, src)) {
if (fputs(buf, dst) == EOF) {
/* Handle error */
}
}
return 0;
}
unsigned long fib1(unsigned int n) {
if (n == 0) {
return 0;
}
else if (n == 1 || n == 2) {
return 1;
}
... | int copy_file(FILE *src, FILE *dst, size_t bufsize) {
if (bufsize == 0) {
/* Handle error */
}
char *buf = (char *)malloc(bufsize);
if (!buf) {
/* Handle error */
}
while (fgets(buf, bufsize, src)) {
if (fputs(buf, dst) == EOF) {
/* Handle error */
}
}
/* ... */
free(buf);
ret... | ## Risk Assessment
Program stacks are frequently used for convenient temporary storage because allocated memory is automatically freed when the function returns. Generally, the operating system grows the stack as needed. However, growing the stack can fail because of a lack of memory or a collision with other allocated... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 08. Memory Management (MEM) |
c | 87,152,115 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152115 | 3 | 8 | MEM06-C | Ensure that sensitive data is not written out to disk | Developers should take steps to prevent sensitive information such as passwords, cryptographic keys, and other secrets from being inadvertently leaked. Preventive measures include attempting to keep such data from being written to disk.
Two common mechanisms by which data is inadvertently written to disk are
swapping
a... | char *secret;
secret = (char *)malloc(size+1);
if (!secret) {
/* Handle error */
}
/* Perform operations using secret... */
memset_s(secret, '\0', size+1);
free(secret);
secret = NULL;
## Noncompliant Code Example
In this noncompliant code example, sensitive information is supposedly stored in the dynamically all... | #include <sys/resource.h>
/* ... */
struct rlimit limit;
limit.rlim_cur = 0;
limit.rlim_max = 0;
if (setrlimit(RLIMIT_CORE, &limit) != 0) {
/* Handle error */
}
char *secret;
secret = (char *)malloc(size+1);
if (!secret) {
/* Handle error */
}
/* Perform operations using secret... */
memset_s(secret, '\0', si... | ## Risk Assessment
Writing sensitive data to disk preserves it for future retrieval by an attacker, who may even be able to bypass the access restrictions of the operating system by using a disk maintenance program.
Recommendation
Severity
Likelihood
Detectable
Repairable
Priority
Level
MEM06-C
Medium
Unlikely
No
No
P2... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 08. Memory Management (MEM) |
c | 87,152,094 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152094 | 3 | 8 | MEM07-C | Ensure that the arguments to calloc(), when multiplied, do not wrap | Deprecated
This guideline does not apply to code that need conform only to C23. Code that must conform to older versions of the C standard should still comply with this guideline.
The
calloc()
function takes two arguments: the number of elements to allocate and the storage size of those elements. Typically,
calloc()
im... | size_t num_elements;
long *buffer = (long *)calloc(num_elements, sizeof(long));
if (buffer == NULL) {
/* Handle error condition */
}
/* ... */
free(buffer);
buffer = NULL;
## Noncompliant Code Example
In this noncompliant example, the user-defined function
get_size()
(not shown) is used to calculate the size requi... | long *buffer;
size_t num_elements;
if (num_elements > SIZE_MAX/sizeof(long)) {
/* Handle error condition */
}
buffer = (long *)calloc(num_elements, sizeof(long));
if (buffer == NULL) {
/* Handle error condition */
}
## Compliant Solution
In this compliant solution, the two arguments
num_elements
and
sizeof(long)
... | ## Risk Assessment
Unsigned integer wrapping in memory allocation functions can lead to buffer overflows that can be
exploited
by an attacker to execute arbitrary code with the permissions of the vulnerable process. Most implementations of
calloc()
now check to make sure silent wrapping does not occur, but it is not al... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 08. Memory Management (MEM) |
c | 87,152,072 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152072 | 3 | 8 | MEM10-C | Define and use a pointer validation function | Many functions accept pointers as arguments. If the function dereferences an
invalid pointer
(as in
) or reads or writes to a pointer that does not refer to an object, the results are
undefined
. Typically, the program will
terminate abnormally
when an invalid pointer is dereferenced, but it is possible for an invalid ... | void incr(int *intptr) {
if (intptr == NULL) {
/* Handle error */
}
(*intptr)++;
}
## Noncompliant Code Example
In this noncompliant code example, the
incr()
function increments the value referenced by its argument. It also ensures that its argument is not a null pointer. But the pointer could still be inval... | void incr(int *intptr) {
if (!valid(intptr)) {
/* Handle error */
}
(*intptr)++;
}
## Compliant Solution
This
incr()
function can be improved by using the
valid()
function. The resulting implementation is less likely to dereference an invalid pointer or write to memory that is outside the bounds of a valid o... | ## Risk Assessment
A pointer validation function can be used to detect and prevent operations from being performed on some invalid pointers.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
MEM10-C
High
Unlikely
No
No
P3
L3
Automated Detection
Tool
Version
Checker
Description
LDRA tool suite
159 S
Enhanced... | SEI CERT C Coding Standard > 3 Recommendations > Rec. 08. Memory Management (MEM) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.