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,074
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152074
3
13
API00-C
Functions should validate their parameters
Redundant testing by caller and by callee as a style of defensive programming is largely discredited in the C and C++ communities, the main problem being performance. The usual discipline in C and C++ is to require validation on only one side of each interface. Requiring the caller to validate arguments can result in f...
/* Sets some internal state in the library */ extern int setfile(FILE *file); /* Performs some action using the file passed earlier */ extern int usefile(); static FILE *myFile; void setfile(FILE *file) { myFile = file; } void usefile(void) { /* Perform some action here */ } ## Noncompliant Code Example In...
/* Sets some internal state in the library */ extern errno_t setfile(FILE *file); /* Performs some action using the file passed earlier */ extern errno_t usefile(void); static FILE *myFile; errno_t setfile(FILE *file) { if (file && !ferror(file) && !feof(file)) { myFile = file; return 0; } /* Error saf...
## Risk Assessment Failing to validate the parameters in library functions may result in an access violation or a data integrity violation. Such a scenario indicates a flaw in how the library is used by the calling code. However, the library itself may still be the vector by which the calling code's vulnerability is ex...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,151,926
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151926
3
13
API01-C
Avoid laying out strings in memory directly before sensitive data
Strings (both character and wide-character) are often subject to buffer overflows, which will overwrite the memory immediately past the string. Many rules warn against buffer overflows, including . Sometimes the danger of buffer overflows can be minimized by ensuring that arranging memory such that data that might be c...
const size_t String_Size = 20; struct node_s { char name[String_Size]; struct node_s* next; } ## Noncompliant Code Example ## This noncompliant code example stores a set of strings using a linked list: #ffcccc c const size_t String_Size = 20; struct node_s { char name[String_Size]; struct node_s* next; } A buffer ...
const size_t String_Size = 20; struct node_s { struct node_s* next; char name[String_Size]; } const size_t String_Size = 20; struct node_s { struct node_s* next; char* name; } ## Compliant Solution ## This compliant solution creates a linked list of strings but stores thenextpointer before the string: #ccccff...
## Risk Assessment Failure to follow this recommendation can result in memory corruption from buffer overflows, which can easily corrupt data or yield remote code execution. Rule Severity Likelihood Detectable Repairable Priority Level API01-C High Likely Yes No P18 L1 Automated Detection Tool Version Checker Descripti...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,290
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152290
3
13
API02-C
Functions that read or write to or from an array should take an argument to specify the source or target size
Functions that have an array as a parameter should also have an additional parameter that indicates the maximum number of elements that can be stored in the array. That parameter is required to ensure that the function does not access memory outside the bounds of the array and adversely influence program execution. It ...
char *strncpy(char * restrict s1, const char * restrict s2, size_t n); char *strncat(char * restrict s1, const char * restrict s2, size_t n); ## Noncompliant Code Example It is not necessary to go beyond the standard C library to find examples that violate this recommendation because the C language often prioritizes p...
char *improved_strncpy(char * restrict s1, size_t s1count, const char * restrict s2, size_t s2count, size_t n); char *improved_strncat(char * restrict s1, size_t s1count, const char * restrict s2, size_t s2count, size_t n); ## Compliant Solution The C strncpy() and strncat() functions could be improved by adding eleme...
## Risk Assessment Failure to follow this recommendation can result in improper memory accesses and buffer overflows that are detrimental to the correct and continued execution of the program. Rule Severity Likelihood Detectable Repairable Priority Level API02-C High Likely Yes No P18 L1 Automated Detection Tool Versio...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,287
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152287
3
13
API03-C
Create consistent interfaces and capabilities across related functions
Related functions, such as those that make up a library, should provide consistent and usable interfaces. Ralph Waldo Emerson said, "A foolish consistency is the hobgoblin of little minds," but inconsistencies in functional interfaces or behavior can lead to erroneous use, so we understand this to be a "wise consistenc...
int fputs(const char * restrict s, FILE * restrict stream); int fprintf(FILE * restrict stream, const char * restrict format, ...); #include <stdio.h> #define fputs(X,Y) fputs(Y,X) ## Noncompliant Code Example (Interface) It is not necessary to go beyond the standard C library to find examples of inconsistent interf...
/* Initialization of pthread attribute objects */ int pthread_condattr_init(pthread_condattr_t *); int pthread_mutexattr_init(pthread_mutexattr_t *); int pthread_rwlockattr_init(pthread_rwlockattr_t *); ... /* Initialization of pthread objects using attributes */ int pthread_cond_init(pthread_cond_t * restrict, const p...
## Risk Assessment Failure to maintain consistency in interfaces and capabilities across functions can result in type errors in the program. Rule Severity Likelihood Detectable Repairable Priority Level API03-C Medium Unlikely No No P2 L3 Related Vulnerabilities Search for vulnerabilities resulting from the violation o...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,244
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152244
3
13
API04-C
Provide a consistent and usable error-checking mechanism
Functions should provide consistent and usable error-checking mechanisms. Complex interfaces are sometimes ignored by programmers, resulting in code that is not error checked. Inconsistent interfaces are frequently misused and difficult to use, resulting in lower-quality code and higher development costs.
char *dir, *file, pname[MAXPATHLEN]; /* ... */ if (strlcpy(pname, dir, sizeof(pname)) >= sizeof(pname)) { /* Handle source-string-too long error */ } ## Noncompliant Code Example (strlcpy()) The strlcpy() function copies a null-terminated source string to a destination array. It is designed to be a safer, more con...
errno_t retValue; string_m dest, source; /* ... */ if (retValue = strcpy_m(dest, source)) { fprintf(stderr, "Error %d from strcpy_m.\n", retValue); } ## Compliant Solution (strcpy_m()) The managed string library [ Burch 2006 ] handles errors by consistently returning the status code in the function return val...
## Risk Assessment Failure to provide a consistent and usable error-checking mechanism can result in type errors in the program. Rule Severity Likelihood Detectable Repairable Priority Level API04-C Medium Unlikely No No P2 L3 Automated Detection Tool Version Checker Description error-information-unused error-informati...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,031
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152031
3
13
API05-C
Use conformant array parameters
Traditionally, C arrays are declared with an index that is either a fixed constant or empty. An array with a fixed constant index indicates to the compiler how much space to reserve for the array. An array declaration with an empty index is an incomplete type and indicates that the variable references a pointer to an a...
void my_memset(char* p, size_t n, char v) { memset( p, v, n); } void my_memset(char p[n], size_t n, char v) { memset( p, v, n); } ## Noncompliant Code Example This code example provides a function that wraps a call to the standard memset() function and has a similar set of arguments. However, although this functi...
void my_memset(size_t n; char p[n], size_t n, char v) { memset(p, v, n); } void my_memset(size_t n, char p[n], char v) { memset(p, v, n); } ## Compliant Solution (GCC) This compliant solution uses a GNU extension to forward declare the size_t variable n before using it in the subsequent array declaration. Consequ...
## Risk Assessment Failing to specify conformant array dimensions increases the likelihood that another developer will invoke the function with out-of-range integers, which could cause an out-of-bounds memory read or write. Rule Severity Likelihood Detectable Repairable Priority Level API05-C High Probable Yes No P12 L...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,337
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152337
3
13
API07-C
Enforce type safety
Upon return, functions should guarantee that any object returned by the function, or any modified value referenced by a pointer argument, is a valid object of function return type or argument type. Otherwise, type errors can occur in the program. A good example is the null-terminated byte string type in C. If a string ...
char *source; char a[NTBS_SIZE]; /* ... */ if (source) { char* b = strncpy(a, source, 5); // b == a } else { /* Handle null string condition */ } ## Noncompliant Code Example The standard strncpy() function does not guarantee that the resulting string is null-terminated. If there is no null character in the first ...
char *source; char a[NTBS_SIZE]; /* ... */ if (source) { errno_t err = strncpy_s(a, sizeof(a), source, 5); if (err != 0) { /* Handle error */ } } else { /* Handle null string condition */ } ## Compliant Solution (strncpy_s(), C11 Annex K) The C11 Annex K strncpy_s() function copies up to n characters from ...
## Risk Assessment Failure to enforce type safety can result in type errors in the program. Rule Severity Likelihood Detectable Repairable Priority Level API07-C Medium Unlikely No No P2 L3 Automated Detection Tool Version Checker Description LANG.CAST.VALUE LANG.CAST.COERCE ALLOC.TM Cast alters value Coercion alters v...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,226
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152226
3
13
API09-C
Compatible values should have the same type
Make sure compatible values have the same type. For example, when the return value of one function is used as an argument to another function, make sure they are the same type. Ensuring compatible values have the same type allows the return value to be passed as an argument to the related function without conversion, r...
ssize_t atomicio(f, fd, _s, n) ssize_t (*f) (int, void *, size_t); int fd; void *_s; size_t n; { char *s = _s; ssize_t res, pos = 0; while (n > pos) { res = (f) (fd, s + pos, n - pos); switch (res) { case -1: if (errno == EINTR || errno == EAGAIN) continue; case 0: ...
size_t atomicio(ssize_t (*f) (int, void *, size_t),  int fd, void *_s, size_t n) { char *s = _s; size_t pos = 0; ssize_t res; struct pollfd pfd; pfd.fd = fd; pfd.events = f == read ? POLLIN : POLLOUT; while (n > pos) { res = (f) (fd, s + pos, n - pos); switch (res) { case -1:...
## Risk Assessment The risk in using in-band error indicators is difficult to quantify and is consequently given as low. However, if the use of in-band error indicators results in programmers' failing to check status codes or incorrectly checking them, the consequences can be more severe. Recommendation Severity Likeli...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,151,961
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151961
3
13
API10-C
APIs should have security options enabled by default
APIS should have security options enabled by default– for example, having best practice cipher suites enabled by default (something that changes over time) while disabling out-of-favor cipher suites by default. When interface stability is also a design requirement, an interface can meet both goals by providing off-by-d...
int tls_connect_by_name(const char *host, int port, int option_bitmask); #define TLS_DEFAULT_OPTIONS 0 #define TLS_VALIDATE_HOST 0x0001 #define TLS_DISABLE_V1_0 0x0002 #define TLS_DISABLE_V1_1 0x0004 ## Noncompliant Code Example If the caller of this API in this noncompliant example doesn't understand what the options...
int tls_connect_by_name(const char *host, int port, int option_bitmask); #define TLS_DEFAULT_OPTIONS 0 #define TLS_DISABLE_HOST_VALIDATION 0x0001 // use rarely, subject to man-in-the-middle attack #define TLS_ENABLE_V1_0 0x0002 #define TLS_ENABLE_V1_1 0x0004 ## Compliant Solution If the caller of this API doesn't und...
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level API10-C Medium Likely No No P6 L3
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,117
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152117
3
6
ARR00-C
Understand how arrays work
The incorrect use of arrays has traditionally been a source of exploitable vulnerabilities . Elements referenced within an array using the subscript operator [] are not checked unless the programmer provides adequate bounds checking. As a result, the expression array [pos] = value can be used by an attacker to transfer...
null
null
## Risk Assessment Arrays are a common source of vulnerabilities in C language programs because they are frequently used but not always fully understood. Recommendation Severity Likelihood Detectable Repairable Priority Level ARR00-C High Probable No No P6 L2 Automated Detection Tool Version Checker Description LANG.CA...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 06. Arrays (ARR)
c
87,152,137
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152137
3
6
ARR01-C
Do not apply the sizeof operator to a pointer when taking the size of an array
The sizeof operator yields the size (in bytes) of its operand, which can be an expression or the parenthesized name of a type. However, using the sizeof operator to determine the size of arrays is error prone. The sizeof operator is often used in determining how much memory to allocate via malloc() . However using an i...
void clear(int array[]) { for (size_t i = 0; i < sizeof(array) / sizeof(array[0]); ++i) { array[i] = 0; } } void dowork(void) { int dis[12]; clear(dis); /* ... */ } enum {ARR_LEN = 100}; void clear(int a[ARR_LEN]) { memset(a, 0, sizeof(a)); /* Error */ } int main(void) { int b[ARR_LEN]; clear...
void clear(int array[], size_t len) { for (size_t i = 0; i < len; i++) { array[i] = 0; } } void dowork(void) { int dis[12]; clear(dis, sizeof(dis) / sizeof(dis[0])); /* ... */ } enum {ARR_LEN = 100}; void clear(int a[], size_t len) { memset(a, 0, len * sizeof(int)); } int main(void) { int b[ARR_L...
## Risk Assessment Incorrectly using the sizeof operator to determine the size of an array can result in a buffer overflow, allowing the execution of arbitrary code. Recommendation Severity Likelihood Detectable Repairable Priority Level ARR01-C High Probable No Yes P12 L1 Automated Detection Tool Version Checker Descr...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 06. Arrays (ARR)
c
87,152,105
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152105
3
6
ARR02-C
Explicitly specify array bounds, even if implicitly defined by an initializer
The C Standard allows an array variable to be declared both with a bound and with an initialization literal. The initialization literal also implies an array bound in the number of elements specified. The size implied by an initialization literal is usually specified by the number of elements, int array[] = {1, 2, 3}; ...
int a[3] = {1, 2, 3, 4}; int a[] = {1, 2, 3, 4}; ## Noncompliant Code Example (Incorrect Size) This noncompliant code example initializes an array of integers using an initialization with too many elements for the array: #FFCCCC c int a[3] = {1, 2, 3, 4}; The size of the array a is 3, although the size of the initial...
int a[4] = {1, 2, 3, 4}; ## Compliant Solution ## This compliant solution explicitly specifies the array bound: #ccccff c int a[4] = {1, 2, 3, 4}; Explicitly specifying the array bound, although it is implicitly defined by an initializer, allows a compiler or other static analysis tool to issue a diagnostic if these v...
## Risk Assessment Recommendation Severity Likelihood Detectable Repairable Priority Level ARR02-C Medium Unlikely Yes Yes P6 L2 Automated Detection Tool Version Checker Description array-size-global Partially checked CertC-ARR02 Fully implemented Compass/ROSE CC2.ARR02 Fully implemented C0678, C0688, C3674, C3684 LDRA...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 06. Arrays (ARR)
c
87,152,322
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152322
2
6
ARR30-C
Do not form or use out-of-bounds pointers or array subscripts
The C Standard identifies the following distinct situations in which undefined behavior (UB) can arise as a result of invalid pointer operations: UB Description Example Code 43 Addition or subtraction of a pointer into, or just beyond, an array object and an integer type produces a result that does not point into, or j...
enum { TABLESIZE = 100 }; static int table[TABLESIZE]; int *f(int index) { if (index < TABLESIZE) { return table + index; } return NULL; } error_status_t _RemoteActivation( /* ... */, WCHAR *pwszObjectName, ... ) { *phr = GetServerPath( pwszObjectName, &pwszObjectName); /* ... */...
enum { TABLESIZE = 100 }; static int table[TABLESIZE]; int *f(int index) { if (index >= 0 && index < TABLESIZE) { return table + index; } return NULL; } #include <stddef.h>   enum { TABLESIZE = 100 }; static int table[TABLESIZE]; int *f(size_t index) { if (index < TABLESIZE) { return table + index;...
## Risk Assessment Writing to out-of-range pointers or array subscripts can result in a buffer overflow and the execution of arbitrary code with the permissions of the vulnerable process. Reading from out-of-range pointers or array subscripts can result in unintended information disclosure. Rule Severity Likelihood Det...
SEI CERT C Coding Standard > 2 Rules > Rule 06. Arrays (ARR)
c
87,152,385
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152385
2
6
ARR32-C
Ensure size arguments for variable length arrays are in a valid range
Variable length arrays (VLAs), a conditionally supported language feature, are essentially the same as traditional C arrays except that they are declared with a size that is not a constant integer expression and can be declared only at block scope or function prototype scope and no linkage. When supported, a variable l...
#include <stddef.h> extern void do_work(int *array, size_t size);   void func(size_t size) { int vla[size]; do_work(vla, size); } #include <stdlib.h> #include <string.h>   enum { N1 = 4096 }; void *func(size_t n2) { typedef int A[n2][N1]; A *array = malloc(sizeof(A)); if (!array) { /* Handle error */ ...
#include <stdint.h> #include <stdlib.h>   enum { MAX_ARRAY = 1024 }; extern void do_work(int *array, size_t size);   void func(size_t size) { if (0 == size || SIZE_MAX / sizeof(int) < size) { /* Handle error */ return; } if (size < MAX_ARRAY) { int vla[size]; do_work(vla, size); } else { int...
## Risk Assessment Failure to properly specify the size of a variable length array may allow arbitrary code execution or result in stack exhaustion. Rule Severity Likelihood Detectable Repairable Priority Level ARR32-C High Probable No No P6 L2 Automated Detection Tool Version Checker Description variable-array-length ...
SEI CERT C Coding Standard > 2 Rules > Rule 06. Arrays (ARR)
c
87,152,341
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152341
2
6
ARR36-C
Do not subtract or compare two pointers that do not refer to the same array
When two pointers are subtracted, both must point to elements of the same array object or just one past the last element of the array object (C Standard, 6.5.7 [ ISO/IEC 9899:2024 ]); the result is the difference of the subscripts of the two array elements. Otherwise, the operation is undefined behavior . (See undefine...
#include <stddef.h>   enum { SIZE = 32 };   void func(void) { int nums[SIZE]; int end; int *next_num_ptr = nums; size_t free_elements; /* Increment next_num_ptr as array fills */ free_elements = &end - next_num_ptr; } ## Noncompliant Code Example In this noncompliant code example, pointer subtraction is ...
#include <stddef.h> enum { SIZE = 32 };   void func(void) { int nums[SIZE]; int *next_num_ptr = nums; size_t free_elements; /* Increment next_num_ptr as array fills */ free_elements = &(nums[SIZE]) - next_num_ptr; } ## Compliant Solution In this compliant solution, the number of free elements is computed b...
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level ARR36-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Description pointer-subtraction pointer-comparison Partially checked CertC-ARR36 Can detect operations on pointers that are unrelated LANG.STRUCT.CUP LANG.STRUCT....
SEI CERT C Coding Standard > 2 Rules > Rule 06. Arrays (ARR)
c
87,152,085
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152085
2
6
ARR37-C
Do not add or subtract an integer to a pointer to a non-array object
Pointer arithmetic must be performed only on pointers that reference elements of array objects. The C Standard, 6.5.7 [ ISO/IEC 9899:2024 ], states the following about pointer arithmetic: When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. I...
struct numbers { short num_a, num_b, num_c; }; int sum_numbers(const struct numbers *numb){ int total = 0; const short *numb_ptr; for (numb_ptr = &numb->num_a; numb_ptr <= &numb->num_c; numb_ptr++) { total += *(numb_ptr); } return total; } int main(void) { struct numbers my_numbers =...
total = numb->num_a + numb->num_b + numb->num_c; #include <stddef.h> struct numbers { short a[3]; }; int sum_numbers(const short *numb, size_t dim) { int total = 0; for (size_t i = 0; i < dim; ++i) { total += numb[i];  } return total; } int main(void) { struct numbers my_numbers = { .a[0]= 1, .a[1]=...
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level ARR37-C Medium Probable Yes No P8 L2 Automated Detection Tool Version Checker Description Supported indirectly via MISRA C:2004 Rule 17.4. CertC-ARR37 Fully implemented LANG.MEM.BO LANG.MEM.BU LANG.STRUCT.PARITH LANG.STRUCT.PBB LANG.STRUCT...
SEI CERT C Coding Standard > 2 Rules > Rule 06. Arrays (ARR)
c
87,151,963
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151963
2
6
ARR38-C
Guarantee that library functions do not form invalid pointers
C library functions that make changes to arrays or objects take at least two arguments: a pointer to the array or object and an integer indicating the number of elements or bytes to be manipulated. For the purposes of this rule, the element count of a pointer is the size of the object to which it points, expressed by t...
null
#include <string.h>   void f2(void) { const size_t ARR_SIZE = 4; long a[ARR_SIZE]; const size_t n = sizeof(a); void *p = a; memset(p, 0, n); } #include <string.h> void f4() { char p[40]; const char *q = "Too short"; size_t n = sizeof(p) < strlen(q) + 1 ? sizeof(p) : strlen(q) + 1; memcpy(p, q, n); ...
null
SEI CERT C Coding Standard > 2 Rules > Rule 06. Arrays (ARR)
c
87,152,330
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152330
2
6
ARR39-C
Do not add or subtract a scaled integer to a pointer
Pointer arithmetic is appropriate only when the pointer argument refers to an array (see ), including an array of bytes. When performing pointer arithmetic, the size of the value to add to or subtract from a pointer is automatically scaled to the size of the type of the referenced array object. Adding or subtracting a ...
enum { INTBUFSIZE = 80 }; extern int getdata(void); int buf[INTBUFSIZE];   void func(void) { int *buf_ptr = buf; while (buf_ptr < (buf + sizeof(buf))) { *buf_ptr++ = getdata(); } } #include <string.h> #include <stdlib.h> #include <stddef.h>   struct big { unsigned long long ull_a; unsigned long long ul...
enum { INTBUFSIZE = 80 }; extern int getdata(void); int buf[INTBUFSIZE]; void func(void) { int *buf_ptr = buf; while (buf_ptr < (buf + INTBUFSIZE)) { *buf_ptr++ = getdata(); } } #include <string.h> #include <stdlib.h> #include <stddef.h>   struct big { unsigned long long ull_a; unsigned long long ull_...
## Risk Assessment Failure to understand and properly use pointer arithmetic can allow an attacker to execute arbitrary code. Rule Severity Likelihood Detectable Repairable Priority Level ARR39-C High Probable No No P6 L2 Automated Detection Tool Version Checker Description scaled-pointer-arithmetic Partially checked B...
SEI CERT C Coding Standard > 2 Rules > Rule 06. Arrays (ARR)
c
87,152,303
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152303
3
14
CON01-C
Acquire and release synchronization primitives in the same module, at the same level of abstraction
All locking and unlocking of mutexes should be performed in the same module and at the same level of abstraction. Failure to follow this recommendation can lead to some lock or unlock operations not being executed by the multithreaded program as designed, eventually resulting in deadlock, race conditions, or other secu...
#include <threads.h> enum { MIN_BALANCE = 50 }; int account_balance; mtx_t mp; /* Initialize mp */ int verify_balance(int amount) { if (account_balance - amount < MIN_BALANCE) { /* Handle error condition */ if (mtx_unlock(&mp) == thrd_error) { /* Handle error */ } return -1; } return 0;...
#include <threads.h> enum { MIN_BALANCE = 50 }; static int account_balance; static mtx_t mp; /* Initialize mp */ static int verify_balance(int amount) { if (account_balance - amount < MIN_BALANCE) { return -1; /* Indicate error to caller */ }  return 0; /* Indicate success to caller */ } int debit(int...
## Risk Assessment Improper use of mutexes can result in denial-of-service attacks or the unexpected termination of a multithreaded program. Recommendation Severity Likelihood Detectable Repairable Priority Level CON01-C Low Probable Yes No P4 L3
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,152,314
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152314
3
14
CON02-C
Do not use volatile as a synchronization primitive
The C Standard, subclause 5.1.2.3, paragraph 2 [ ISO/IEC 9899:2011 ], says: Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression in genera...
bool flag = false; void test() { while (!flag) { sleep(1000); } } void wakeup(){ flag = true; } void debit(unsigned int amount){ test(); account_balance -= amount; } volatile bool flag = false; void test() { while (!flag){ sleep(1000); } } void wakeup(){ flag = true; } void debit(unsigned...
#include <threads.h> int account_balance; mtx_t flag; /* Initialize flag */ int debit(unsigned int amount) { if (mtx_lock(&flag) == thrd_error) { return -1; /* Indicate error */ }  account_balance -= amount; /* Inside critical section */  if (mtx_unlock(&flag) == thrd_error) { return -1; /* Indica...
## Risk Assessment Recommendation Severity Likelihood Detectable Repairable Priority Level CON02-C Medium Probable No No P4 L3
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,152,036
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152036
3
14
CON03-C
Ensure visibility when accessing shared variables
Reading a shared primitive variable in one thread may not yield the value of the most recent write to the variable from another thread. Consequently, the thread may observe a stale value of the shared variable. To ensure the visibility of the most recent update, the write to the variable must happen before the read (C ...
final class ControlledStop implements Runnable { private boolean done = false; @Override public void run() { while (!done) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset int...
final class ControlledStop implements Runnable { private volatile boolean done = false; @Override public void run() { while (!done) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // ...
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level CON03-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Description Supported, but no explicit checker C1765 C1766
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,152,305
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152305
3
14
CON04-C
Join or detach threads even if their exit status is unimportant
The thrd_detach() function is used to tell the underlying system that resources allocated to a particular thread can be reclaimed once it terminates. This function should be used when a thread's exit status is not required by other threads (and no other thread needs to use thrd_join() to wait for it to complete). Whene...
#include <stdio.h> #include <threads.h>   const size_t thread_no = 5; const char mess[] = "This is a test"; int message_print(void *ptr){ const char *msg = (const char *) ptr; printf("THREAD: This is the Message %s\n", msg); return 0; } int main(void){ /* Create a pool of threads */ thrd_t thr[thread_no]; ...
#include <stdio.h> #include <threads.h>   const size_t thread_no = 5; const char mess[] = "This is a test"; int message_print(void *ptr){ const char *msg = (const char *)ptr; printf("THREAD: This is the Message %s\n", msg);   /* Detach the thread, check the return code for errors */ if (thrd_detach(thrd_curren...
## Risk Assessment Recommendation Severity Likelihood Detectable Repairable Priority Level CON04-C Low Unlikely Yes No P2 L3 Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,151,981
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151981
3
14
CON05-C
Do not perform operations that can block while holding a lock
If a lock is being held and an operation that can block is performed, any other thread that needs to acquire that lock may also block. This condition can degrade system performance or cause a deadlock to occur.  Blocking calls include, but are not limited to, network, file, and console I/O. Using a blocking operation w...
#include <stdio.h> #include <threads.h>   mtx_t mutex; int thread_foo(void *ptr) { int result; FILE *fp; if ((result = mtx_lock(&mutex)) != thrd_success) { /* Handle error */ }   fp = fopen("SomeNetworkFile", "r"); if (fp != NULL) { /* Work with the file */ fclose(fp); }   if ((result = mt...
#include <stdio.h> #include <threads.h>   mtx_t mutex;   int thread_foo(void *ptr) { int result; FILE *fp = fopen("SomeNetworkFile", "r");   if (fp != NULL) { /* Work with the file */ fclose(fp); } if ((result = mtx_lock(&mutex)) != thrd_success) { /* Handle error */ } /* ... */ if ((resu...
## Risk Assessment Blocking or lengthy operations performed within synchronized regions could result in a deadlocked or an unresponsive system. Recommendation Severity Likelihood Detectable Repairable Priority Level CON05-C Low Probable No No P2 L3 Automated Detection Tool Version Checker Description CONCURRENCY.STARVE...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,151,935
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151935
3
14
CON06-C
Ensure that every mutex outlives the data it protects
## ********** Text below this note not yet converted from Java to C! ************ Programs must not use instance locks to protect static shared data because instance locks are ineffective when two or more instances of the class are created. Consequently, failure to use a static lock object leaves the shared state unpro...
## Noncompliant Code Example (Nonstatic Lock Object for Static Data) This noncompliant code example attempts to guard access to the static counter field using a non-static lock object. When two Runnable tasks are started, they create two instances of the lock object and lock on each instance separately. public final cl...
## Compliant Solution (Static Lock Object) ## This compliant solution ensures the atomicity of the increment operation by locking on a static object. public class CountBoxes implements Runnable { private static int counter; // ... private static final Object lock = new Object(); public void run() { synchronized (lock) ...
## Risk Assessment Using an instance lock to protect static shared data can result in nondeterministic behavior. Rule Severity Likelihood Detectable Repairable Priority Level CON06-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Description Supported, but no explicit checker
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,151,920
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151920
3
14
CON07-C
Ensure that compound operations on shared variables are atomic
Compound operations are operations that consist of more than one discrete operation. Expressions that include postfix or prefix increment ( ++ ), postfix or prefix decrement ( -- ), or compound assignment operators always result in compound operations. Compound assignment expressions use operators such as *= , /= , %= ...
null
null
null
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,151,947
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151947
3
14
CON08-C
Do not assume that a group of calls to independently atomic methods is atomic
A consistent locking policy guarantees that multiple threads cannot simultaneously access or modify shared data. When two or more operations must be performed as a single atomic operation, a consistent locking policy must be implemented using some form of locking, such as a mutex. In the absence of such a policy, the c...
null
null
null
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,151,982
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151982
3
14
CON09-C
Avoid the ABA problem when using lock-free algorithms
Lock-free programming is a technique that allows concurrent updates of shared data structures without using explicit locks. This method ensures that no threads block for arbitrarily long times, and it thereby boosts performance. Lock-free programming has the following advantages: Can be used in places where locks must ...
#include <stdatomic.h>   /* * Sets index to point to index of maximum element in array * and value to contain maximum array value.  */ void find_max_element(atomic_int array[], size_t *index, int *value); static atomic_int array[]; void func(void) { size_t index; int value; find_max_element(array, &index, &va...
#include <stdatomic.h> #include <threads.h>   static atomic_int array[]; static mtx_t array_mutex; void func(void) { size_t index; int value; if (thrd_success != mtx_lock(&array_mutex)) { /* Handle error */ } find_max_element(array, &index, &value); /* ... */ if (!atomic_compare_exchange_strong(array...
## Risk Assessment The likelihood of having a race condition is low. Once the race condition occurs, the reading memory that has already been freed can lead to abnormal program termination or unintended information disclosure. Recommendation Severity Likelihood Detectable Repairable Priority Level CON09-C Medium Unlike...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,152,258
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152258
2
14
CON30-C
Clean up thread-specific storage
The tss_create() function creates a thread-specific storage pointer identified by a key. Threads can allocate thread-specific storage and associate the storage with a key that uniquely identifies the storage by calling the tss_set() function. If not properly freed, this memory may be leaked. Ensure that thread-specific...
#include <threads.h> #include <stdlib.h> /* Global key to the thread-specific storage */ tss_t key; enum { MAX_THREADS = 3 }; int *get_data(void) { int *arr = (int *)malloc(2 * sizeof(int)); if (arr == NULL) { return arr; /* Report error */ } arr[0] = 10; arr[1] = 42; return arr; } int add_data(voi...
#include <threads.h> #include <stdlib.h> /* Global key to the thread-specific storage */ tss_t key; int function(void *dummy) { if (add_data() != 0) { return -1; /* Report error */ } print_data(); free(tss_get(key)); return 0; } /* ... Other functions are unchanged */ #include <threads.h> #include <...
## Risk Assessment Failing to free thread-specific objects results in memory leaks and could result in a denial-of-service attack . Rule Severity Likelihood Detectable Repairable Priority Level CON30-C Medium Unlikely No No P2 L3
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,152,173
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152173
2
14
CON31-C
Do not destroy a mutex while it is locked
Mutexes are used to protect shared data structures being concurrently accessed. If a mutex is destroyed while a thread is blocked waiting for that mutex, critical sections and shared data are no longer protected. The C Standard, 7.28.4.1, paragraph 2 [ ISO/IEC 9899:2024 ], states The mtx_destroy function releases any r...
#include <stdatomic.h> #include <stddef.h> #include <threads.h>   mtx_t lock; /* Atomic so multiple threads can modify safely */ atomic_int completed = ATOMIC_VAR_INIT(0); enum { max_threads = 5 }; int do_work(void *arg) { int *i = (int *)arg; if (*i == 0) { /* Creation thread */ if (thrd_success != mtx_init...
#include <stdatomic.h> #include <stddef.h> #include <threads.h>   mtx_t lock; /* Atomic so multiple threads can increment safely */ atomic_int completed = ATOMIC_VAR_INIT(0); enum { max_threads = 5 }; int do_work(void *dummy) { if (thrd_success != mtx_lock(&lock)) { /* Handle error */ } /* Access data prote...
## Risk Assessment Destroying a mutex while it is locked may result in invalid control flow and data corruption. Rule Severity Likelihood Detectable Repairable Priority Level CON31-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Description Supported, but no explicit checker CONCURRENCY.LOCALARG ...
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,152,069
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152069
2
14
CON32-C
Prevent data races when accessing bit-fields from multiple threads
When accessing a bit-field, a thread may inadvertently access a separate bit-field in adjacent memory. This is because compilers are required to store multiple adjacent bit-fields in one storage unit whenever they fit. Consequently, data races may exist not just on a bit-field accessed by multiple threads but also on o...
struct multi_threaded_flags { unsigned int flag1 : 2; unsigned int flag2 : 2; }; struct multi_threaded_flags flags; int thread1(void *arg) { flags.flag1 = 1; return 0; } int thread2(void *arg) { flags.flag2 = 2; return 0; } Thread 1: register 0 = flags Thread 1: register 0 &= ~mask(flag1) Thread 2: regi...
#include <threads.h>   struct multi_threaded_flags { unsigned int flag1 : 2; unsigned int flag2 : 2; }; struct mtf_mutex { struct multi_threaded_flags s; mtx_t mutex; }; struct mtf_mutex flags; int thread1(void *arg) { if (thrd_success != mtx_lock(&flags.mutex)) { /* Handle error */ } flags.s.flag1...
## Risk Assessment Although the race window is narrow, an assignment or an expression can evaluate improperly because of misinterpreted data resulting in a corrupted running state or unintended information disclosure. Rule Severity Likelihood Detectable Repairable Priority Level CON32-C Medium Probable No No P4 L3
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,152,247
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152247
2
14
CON33-C
Avoid race conditions when using library functions
Some C standard library functions are not guaranteed to be reentrant with respect to threads. Functions such as strtok() and asctime() return a pointer to the result stored in function-allocated memory on a per-process basis. Other functions such as rand() store state information in function-allocated memory on a per-p...
#include <errno.h> #include <stdio.h> #include <string.h>   void f(FILE *fp) { fpos_t pos; errno = 0; if (0 != fgetpos(fp, &pos)) { char *errmsg = strerror(errno); printf("Could not get the file position: %s\n", errmsg); } } ## Noncompliant Code Example In this noncompliant code example, the function ...
#include <errno.h> #include <stdio.h> #include <string.h> enum { BUFFERSIZE = 64 };   void f(FILE *fp) { fpos_t pos; errno = 0; if (0 != fgetpos(fp, &pos)) { char errmsg[BUFFERSIZE]; if (strerror_r(errno, errmsg, BUFFERSIZE) != 0) { /* Handle error */ } printf("Could not get the file posit...
## Risk Assessment Race conditions caused by multiple threads invoking the same library function can lead to abnormal termination of the application, data integrity violations, or a denial-of-service attack . Rule Severity Likelihood Detectable Repairable Priority Level CON33-C Medium Probable No No P4 L3 Related Vulne...
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,152,300
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152300
2
14
CON34-C
Declare objects shared between threads with appropriate storage durations
Accessing the automatic or thread-local variables of one thread from another thread is implementation-defined behavior and can cause invalid memory accesses because the execution of threads can be interwoven within the constraints of the synchronization model. As a result, the referenced stack frame or thread-local var...
#include <threads.h> #include <stdio.h> int child_thread(void *val) { int *res = (int *)val; printf("Result: %d\n", *res); return 0; } void create_thread(thrd_t *tid) { int val = 1; if (thrd_success != thrd_create(tid, child_thread, &val)) { /* Handle error */ } } int main(void) { thrd_t tid; cre...
#include <threads.h> #include <stdio.h> int child_thread(void *v) { int *result = (int *)v; printf("Result: %d\n", *result); /* Correctly prints 1 */ return 0; } void create_thread(thrd_t *tid) { static int val = 1; if (thrd_success != thrd_create(tid, child_thread, &val)) { /* Handle error */ } } ...
## Risk Assessment Threads that reference the stack of other threads can potentially overwrite important information on the stack, such as function pointers and return addresses. The compiler may not generate warnings if the programmer allows one thread to access another thread's local variables, so a programmer may no...
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,152,261
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152261
2
14
CON35-C
Avoid deadlock by locking in a predefined order
Mutexes are used to prevent multiple threads from causing a data race by accessing shared resources at the same time. Sometimes, when locking mutexes, multiple threads hold each other's lock, and the program consequently deadlocks. Four conditions are required for deadlock to occur: Mutual exclusion Hold and wait No pr...
#include <stdlib.h> #include <threads.h>   typedef struct { int balance; mtx_t balance_mutex; } bank_account; typedef struct { bank_account *from; bank_account *to; int amount; } transaction; void create_bank_account(bank_account **ba, int initial_amount) { bank_account *nba = (ba...
#include <stdlib.h> #include <threads.h>   typedef struct { int balance; mtx_t balance_mutex;   /* Should not change after initialization */ unsigned int id; } bank_account; typedef struct { bank_account *from; bank_account *to; int amount; } transaction; unsigned int global_id = 1; void create_bank_ac...
## Risk Assessment Deadlock prevents multiple threads from progressing, halting program execution. A denial-of-service attack is possible if the attacker can create the conditions for deadlock. Rule Severity Likelihood Detectable Repairable Priority Level CON35-C Low Probable No No P2 L3 Related Vulnerabilities Search ...
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,151,940
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151940
2
14
CON36-C
Wrap functions that can spuriously wake up in a loop
The cnd_wait() and cnd_timedwait() functions temporarily cede possession of a mutex so that other threads that may be requesting the mutex can proceed. These functions must always be called from code that is protected by locking a mutex. The waiting thread resumes execution only after it has been notified, generally as...
#include <stddef.h> #include <threads.h>   struct node_t { void *node; struct node_t *next; }; struct node_t list; static mtx_t lock; static cnd_t condition; void consume_list_element(void) { if (thrd_success != mtx_lock(&lock)) { /* Handle error */ } if (list.next == NULL) { if (thrd_success !=...
#include <stddef.h> #include <threads.h>   struct node_t { void *node; struct node_t *next; }; struct node_t list; static mtx_t lock; static cnd_t condition; void consume_list_element(void) { if (thrd_success != mtx_lock(&lock)) { /* Handle error */ } while (list.next == NULL) { if (thrd_success...
null
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,152,323
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152323
2
14
CON37-C
Do not call signal() in a multithreaded program
Calling the signal() function in a multithreaded program is undefined behavior . (See undefined behavior 135 .)
#include <signal.h> #include <stddef.h> #include <threads.h>   volatile sig_atomic_t flag = 0; void handler(int signum) { flag = 1; } /* Runs until user sends SIGUSR1 */ int func(void *data) { while (!flag) { /* ... */ } return 0; } int main(void) { signal(SIGUSR1, handler); /* Undefined behavior */ ...
#include <stdatomic.h> #include <stdbool.h> #include <stddef.h> #include <threads.h>   atomic_bool flag = ATOMIC_VAR_INIT(false); int func(void *data) { while (!flag) { /* ... */ } return 0; } int main(void) { thrd_t tid; if (thrd_success != thrd_create(&tid, func, NULL)) { /* Handle error */ }...
## Risk Assessment Mixing signals and threads causes undefined behavior 135 . Rule Severity Likelihood Detectable Repairable Priority Level CON37-C Low Probable Yes No P4 L3 Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,152,023
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152023
2
14
CON38-C
Preserve thread safety and liveness when using condition variables
Both thread safety and liveness are concerns when using condition variables. The thread-safety property requires that all objects maintain consistent states in a multithreaded environment [ Lea 2000 ]. The liveness property requires that every operation or function invocation execute to completion without interruption;...
#include <stdio.h> #include <threads.h> enum { NTHREADS = 5 }; mtx_t mutex; cnd_t cond; int run_step(void *t) { static size_t current_step = 0; size_t my_step = *(size_t *)t; if (thrd_success != mtx_lock(&mutex)) { /* Handle error */ } printf("Thread %zu has the lock\n", my_step); while (current_st...
#include <stdio.h> #include <threads.h> mtx_t mutex; cnd_t cond; int run_step(void *t) { static size_t current_step = 0; size_t my_step = *(size_t *)t; if (thrd_success != mtx_lock(&mutex)) { /* Handle error */ } printf("Thread %zu has the lock\n", my_step); while (current_step != my_step) { pri...
## Risk Assessment Failing to preserve the thread safety and liveness of a program when using condition variables can lead to indefinite blocking and denial of service (DoS). Rule Severity Likelihood Detectable Repairable Priority Level CON38-C Low Unlikely No Yes P2 L3 Automated Detection Tool Version Checker Descript...
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,151,919
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151919
2
14
CON39-C
Do not join or detach a thread that was previously joined or detached
The C Standard, 7.28.5.6 paragraph 2 [ ISO/IEC 9899:2024 ], states that a thread shall not be joined once it was previously joined or detached. The termination of the other thread synchronizes with the completion of the thrd_join function. The thread identified by thr shall not have been previously detached or joined w...
#include <stddef.h> #include <threads.h>   int thread_func(void *arg) { /* Do work */ thrd_detach(thrd_current()); return 0; } int main(void) { thrd_t t; if (thrd_success != thrd_create(&t, thread_func, NULL)) { /* Handle error */ return 0; } if (thrd_success != thrd_join(t, 0)) { /* Handle...
#include <stddef.h> #include <threads.h>    int thread_func(void *arg) {   /* Do work */   return 0; } int main(void) {   thrd_t t;   if (thrd_success != thrd_create(&t, thread_func, NULL)) {     /* Handle error */     return 0;   }   if (thrd_success != thrd_join(t, 0)) {     /* Handle error */     return 0;   }   ...
## Risk Assessment Joining or detaching a previously joined or detached thread is undefined behavior 211 . Rule Severity Likelihood Detectable Repairable Priority Level CON39-C Low Likely No No P3 L3 Automated Detection Tool Version Checker Description invalid-thread-operation Partially checked + soundly supported CONC...
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,151,922
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151922
2
14
CON40-C
Do not refer to an atomic variable twice in an expression
A consistent locking policy guarantees that multiple threads cannot simultaneously access or modify shared data. Atomic variables eliminate the need for locks by guaranteeing thread safety when certain operations are performed on them. The thread-safe operations on atomic variables are specified in the C Standard, subc...
null
null
null
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,151,936
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151936
2
14
CON41-C
Wrap functions that can fail spuriously in a loop
Functions that can fail spuriously should be wrapped in a loop.  The atomic_compare_exchange_weak() and atomic_compare_exchange_weak_explicit() functions both attempt to set an atomic variable to a new value but only if it currently possesses a known old value. Unlike the related functions atomic_compare_exchange_stron...
null
null
null
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,152,000
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152000
2
14
CON42-C
Don't allow attackers to influence environment variables that control concurrency parameters
Under Construction This rule is under construction. The recommended way to use OpenMP is to specify most of the performance parameters in environment variables so that administrators can tweak them for their environment: For example, Set the default number of threads to use. – OMP_NUM_THREADS int_literal OpenMP added a...
null
null
null
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,152,076
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152076
2
14
CON43-C
Do not allow data races in multithreaded code
When multiple threads can read or modify the same data, use synchronization techniques to avoid software flaws that can lead to security vulnerabilities . Data races can often result in abnormal termination or denial of service , but it is possible for them to result in more serious vulnerabilities. The C Standard, sec...
static volatile int account_balance; void debit(int amount) { account_balance -= amount; } void credit(int amount) { account_balance += amount; } #include <stdio.h> void doStuff(int *ps) { switch (*ps) { case 0: { printf("0"); break; } case 1: { printf("1"); break; } case 2: { printf("2"); break;...
#include <threads.h> static int account_balance; static mtx_t account_lock;   int debit(int amount) { if (mtx_lock(&account_lock) == thrd_error) { return -1; /* Indicate error to caller */ } account_balance -= amount; if (mtx_unlock(&account_lock) == thrd_error) { return -1; /* Indicate error to ca...
## Risk Assessment Race conditions caused by multiple threads concurrently accessing and modifying the same data can lead to abnormal termination and denial-of-service attacks or data integrity violations. Recommendation Severity Likelihood Detectable Repairable Priority Level CON43-C Medium Probable No No P4 L3
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
c
87,152,463
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152463
3
2
DCL00-C
Const-qualify immutable objects
Immutable objects should be const -qualified. Enforcing object immutability using const qualification helps ensure the correctness and security of applications. ISO/IEC TR 24772, for example, recommends labeling parameters as constant to avoid the unintentional modification of function arguments [ ISO/IEC TR 24772 ]. d...
float pi = 3.14159f; float degrees; float radians; /* ... */ radians = degrees * pi / 180; ## Noncompliant Code Example In this noncompliant code, pi is declared as a float . Although pi is a mathematical constant, its value is not protected from accidental modification. #FFCCCC c float pi = 3.14159f; float degrees; f...
const float pi = 3.14159f; float degrees; float radians; /* ... */ radians = degrees * pi / 180; ## Compliant Solution ## In this compliant solution,piis declared as aconst-qualified object: #ccccff c const float pi = 3.14159f; float degrees; float radians; /* ... */ radians = degrees * pi / 180;
## Risk Assessment Failing to const -qualify immutable objects can result in a constant being modified at runtime. Recommendation Severity Likelihood Detectable Repairable Priority Level DCL00-C Low Unlikely Yes Yes P3 L3 Automated Detection Tool Version Checker Description parameter-missing-const Partially checked Cer...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,192
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152192
3
2
DCL01-C
Do not reuse variable names in subscopes
Do not use the same variable name in two scopes where one scope is contained in another. For example, No other variable should share the name of a global variable if the other variable is in a subscope of the global variable. A block should not declare a variable with the same name as a variable declared in any block t...
#include <stdio.h>   static char msg[100]; static const size_t msgsize = sizeof( msg); void report_error(const char *str) { char msg[80]; snprintf(msg, msgsize, "Error: %s\n", str); /* ... */ } int main(void) { /* ... */ report_error("some error");   return 0; } void f(void) { for (int i = 0; i < 10; i...
#include <stdio.h>   static char message[100]; static const size_t message_size = sizeof( message); void report_error(const char *str) { char msg[80]; snprintf(msg, sizeof( msg), "Error: %s\n", str); /* ... */ } int main(void) { /* ... */ report_error("some error");   return 0; } void f(void) { for (in...
## Risk Assessment Reusing a variable name in a subscope can lead to unintentionally referencing an incorrect variable. Recommendation Severity Likelihood Detectable Repairable Priority Level DCL01-C Low Unlikely Yes Yes P3 L3 Automated Detection Tool Version Checker Description identifier-hidden Fully checked CertC-DC...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,407
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152407
3
2
DCL02-C
Use visually distinct identifiers
Use visually distinct identifiers with meaningful names to eliminate errors resulting from misreading the spelling of an identifier during the development and review of code. An identifier can denote an object; a function; a tag or a member of a structure, union, or enumeration; a typedef name; a label name; a macro na...
int id_O; /* (Capital letter O) */ int id_0; /* (Numeric digit zero) */ ## Noncompliant Code Example (Source Character Set) DCL02-C implicitly assumes global scope , which can be confused with scope within the same file . Although it may not generate any errors, a possible violation of the rule may occur, as in the f...
int id_a; int id_b; ## Compliant Solution (Source Character Set) ## In a compliant solution, use of visually similar identifiers should be avoided in the same project scope. In file foo.h : #ccccff c int id_a; In file bar.h : #ccccff c int id_b;
## Risk Assessment Failing to use visually distinct identifiers can result in referencing the wrong object or function, causing unintended program behavior. Recommendation Severity Likelihood Detectable Repairable Priority Level DCL02-C Low Unlikely Yes Yes P3 L3 Automated Detection Tool Version Checker Description Cer...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,090
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152090
3
2
DCL03-C
Use a static assertion to test the value of a constant expression
Assertions are a valuable diagnostic tool for finding and eliminating software defects that may result in vulnerabilities (see ). The runtime assert() macro has some limitations, however, in that it incurs a runtime overhead and because it calls abort() . Consequently, the runtime assert() macro is useful only for iden...
#include <assert.h>   struct timer { unsigned char MODE; unsigned int DATA; unsigned int COUNT; }; int func(void) { assert(sizeof(struct timer) == sizeof(unsigned char) + sizeof(unsigned int) + sizeof(unsigned int)); } ## Noncompliant Code Example This noncompliant code uses the assert() macro to assert a pr...
struct timer { unsigned char MODE; unsigned int DATA; unsigned int COUNT; }; #if (sizeof(struct timer) != (sizeof(unsigned char) + sizeof(unsigned int) + sizeof(unsigned int))) #error "Structure must not have any padding" #endif #include <assert.h>   struct timer { unsigned char MODE; unsigned int DATA; ...
## Risk Assessment Static assertion is a valuable diagnostic tool for finding and eliminating software defects that may result in vulnerabilities at compile time. The absence of static assertions, however, does not mean that code is incorrect. Recommendation Severity Likelihood Detectable Repairable Priority Level DCL0...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,402
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152402
3
2
DCL04-C
Do not declare more than one variable per declaration
Every declaration should be for a single variable, on its own line, with an explanatory comment about the role of the variable. Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values. If more than one variable is declared in a declaration, ...
char *src = 0, c = 0; int i, j = 1; ## Noncompliant Code Example In this noncompliant code example, a programmer or code reviewer might mistakenly believe that the two variables src and c are declared as char * . In fact, src has a type of char * , whereas c has a type of char . #FFcccc c char *src = 0, c = 0; ## Non...
char *src; /* Source string */ char c; /* Character being tested */ int i = 1; int j = 1; ## Compliant Solution ## In this compliant solution, each variable is declared on a separate line: #ccccff c char *src; /* Source string */ char c; /* Character being tested */ Although this change has no effec...
## Risk Assessment Declaring no more than one variable per declaration can make code easier to read and eliminate confusion. Recommendation Severity Likelihood Detectable Repairable Priority Level DCL04-C Low Unlikely Yes Yes P3 L3 Automated Detection Tool Version Checker Description multi-declaration Fully checked Cer...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,187
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152187
3
2
DCL05-C
Use typedefs of non-pointer types only
Using type definitions ( typedef ) can often improve code readability. However, type definitions to pointer types can make it more difficult to write const -correct code because the const qualifier will be applied to the pointer type, not to the underlying declared type.
struct obj { int i; float f; }; typedef struct obj *ObjectPtr;   void func(const ObjectPtr o) { /* Can actually modify o's contents, against expectations */ } #include <Windows.h> /* typedef char *LPSTR; */   void func(const LPSTR str) { /* Can mutate str's contents, against expectations */ } #include <Window...
struct obj { int i; float f; }; typedef struct obj Object; void func(const Object *o) { /* Cannot modify o's contents */ } #include <Windows.h> /* typedef const char *LPCSTR; */   void func(LPCSTR str) { /* Cannot modify str's contents */ } #include <Windows.h> /* typedef struct tagPOINT { long x, y; ...
## Risk Assessment Code readability is important for discovering and eliminating vulnerabilities . Recommendation Severity Likelihood Detectable Repairable Priority Level DCL05-C Low Unlikely Yes No P2 L3 Automated Detection Tool Version Checker Description pointer-typedef Fully checked CertC-DCL05 LANG.STRUCT.PIT Poin...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,130
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152130
3
2
DCL06-C
Use meaningful symbolic constants to represent literal values
The C language provides several different kinds of constants: integer constants, such as 10 and 0x1C ; floating constants, such as 1.0 and 6.022e+23 ; and character constants, such as 'a' and '\x10' . C also provides string literals, such as "hello, world" and "\n" . These constants can all be referred to as literals ....
/* ... */ if (age >= 18) { /* Take action */ } else { /* Take a different action */ } /* ... */ char buffer[256]; /* ... */ fgets(buffer, 256, stdin); LDAP *ld = ldap_init("localhost", 1234); if (ld == NULL) { perror("ldap_init"); return(1); } ## Noncompliant Code Example The meaning of the integer literal ...
enum { ADULT_AGE=18 }; /* ... */ if (age >= ADULT_AGE) { /* Take action */ } else { /* Take a different action */ } /* ... */ enum { BUFFER_SIZE=256 }; char buffer[BUFFER_SIZE]; /* ... */ fgets(buffer, BUFFER_SIZE, stdin); char buffer[256]; /* ... */ fgets(buffer, sizeof(buffer), stdin); #ifndef PORTNUMBER ...
## Risk Assessment Using numeric literals makes code more difficult to read and understand. Buffer overruns are frequently a consequence of a magic number being changed in one place (such as in an array declaration) but not elsewhere (such as in a loop through an array). Recommendation Severity Likelihood Detectable Re...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,364
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152364
3
2
DCL07-C
Include the appropriate type information in function declarators
Function declarators must be declared with the appropriate type information, including a return type and parameter list. If type information is not properly specified in a function declarator, the compiler cannot properly check function type information. When using standard library calls, the easiest (and preferred) wa...
int max(a, b) int a, b; { return a > b ? a : b; } /* file_a.c source file */ int func(int one, int two, int three){ printf("%d %d %d", one, two, three); return 1; } /* file_b.c source file */ func(1, 2); int add(int x, int y, int z) { return x + y + z; } int main(int argc, char *argv[]) { int (*fn_ptr) (i...
int max(int a, int b) { return a > b ? a : b; } /* file_b.c source file */ int func(int, int, int); func(1, 2, 3); int add(int x, int y, int z) { return x + y + z; } int main(int argc, char *argv[]) { int (*fn_ptr) (int, int, int) ; int res; fn_ptr = add; res = fn_ptr(2, 3, 4); /* ... */ return 0; }...
## Risk Assessment Failing to include type information for function declarators can result in unexpected or unintended program behavior. Recommendation Severity Likelihood Detectable Repairable Priority Level DCL07-C Low Unlikely Yes No P2 L3 Automated Detection Tool Version Checker Description function-prototype impli...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,145
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152145
3
2
DCL08-C
Properly encode relationships in constant definitions
If a relation exists between constants, you should encode the relationship in the definitions. Do not give two independent definitions, because a maintainer may fail to preserve that relationship when modifying the code. As a corollary, do not encode an impermanent or false relationship between constants, because futur...
enum { IN_STR_LEN=18, OUT_STR_LEN=20 }; enum { ADULT_AGE=18 }; /* Misleading; relationship established when none exists */ enum { ALCOHOL_AGE=ADULT_AGE+3 }; ## Noncompliant Code Example In this noncompliant code example, the definition for OUT_STR_LEN must always be two greater than the definition of IN_STR_LEN . Th...
enum { IN_STR_LEN=18, OUT_STR_LEN=IN_STR_LEN+2 }; enum { ADULT_AGE=18 }; enum { ALCOHOL_AGE=21 }; ## Compliant Solution ## The declaration in this compliant solution embodies the relationship between the two definitions: #ccccff c enum { IN_STR_LEN=18, OUT_STR_LEN=IN_STR_LEN+2 }; As a result, a programmer can reliabl...
## Risk Assessment Failing to properly encode relationships in constant definitions may lead to the introduction of defects during maintenance. These defects could potentially result in vulnerabilities , for example, if the affected constants were used for allocating or accessing memory. Recommendation Severity Likelih...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,089
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152089
3
2
DCL09-C
Declare functions that return errno with a return type of errno_t
When developing new code, declare functions that return errno with a return type of errno_t .  Many existing functions that return errno are declared as returning a value of type int . It is semantically unclear by inspecting the function declaration or prototype if these functions return an error status or a value or,...
## This noncompliant code example nevertheless complies with.
#define __STDC_WANT_LIB_EXT1__ 1   #include <errno.h> #include <stdio.h> #include <stdlib.h>      enum { NO_FILE_POS_VALUES = 3 }; errno_t opener( FILE *file, size_t *width, size_t *height, size_t *data_offset ) { size_t file_w; size_t file_h; size_t file_o; fpos_t offset; if (NULL == file) { return...
## Risk Assessment Failing to test for error conditions can lead to vulnerabilities of varying severity. Declaring functions that return an errno with a return type of errno_t will not eliminate this problem but may reduce errors caused by programmers' misunderstanding the purpose of a return value. Recommendation Seve...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,093
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152093
3
2
DCL10-C
Maintain the contract between the writer and caller of variadic functions
Variadic functions accept a variable number of arguments but are problematic. Variadic functions define an implicit contract between the function writer and the function user that allows the function to determine the number of arguments passed in any particular invocation. Failure to enforce this contract may result in...
int avg = average(1, 4, 6, 4, 1); const char *error_msg = "Resource not available to user."; /* ... */ printf("Error (%s): %s", error_msg); ## Noncompliant Code Example ## In this noncompliant code example, theaverage()function is called as follows: #ffcccc c int avg = average(1, 4, 6, 4, 1); The omission of the va_e...
int avg = average(1, 4, 6, 4, 1, va_eol); const char *error_msg = "Resource not available to user."; /* ... */ printf("Error: %s", error_msg); ## Compliant Solution ## This compliant solution enforces the contract by addingva_eolas the final argument: #ccccff c int avg = average(1, 4, 6, 4, 1, va_eol); ## Compliant S...
## Risk Assessment Incorrectly using a variadic function can result in abnormal program termination or unintended information disclosure. Recommendation Severity Likelihood Detectable Repairable Priority Level DCL10-C High Probable No No P6 L2 Related Vulnerabilities Search for vulnerabilities resulting from the violat...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,357
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152357
3
2
DCL11-C
Understand the type issues associated with variadic functions
The variable parameters of a variadic function—that is, those that correspond with the position of the ellipsis—are interpreted by the va_arg() macro. The va_arg() macro is used to extract the next argument from an initialized argument list within the body of a variadic function implementation. The size of each paramet...
const char *error_msg = "Error occurred"; /* ... */ printf("%s:%d", 15, error_msg); long long a = 1; const char msg[] = "Default message"; /* ... */ printf("%d %s", a, msg); char* string = NULL; printf("%s %d\n", string, 1); ## Noncompliant Code Example (Type Interpretation Error) The C printf() function is implemen...
const char *error_msg = "Error occurred"; /* ... */ printf("%d:%s", 15, error_msg); long long a = 1; const char msg[] = "Default message"; /* ... */ printf("%lld %s", a, msg); char* string = NULL; printf("%s %d\n", (string ? string : "null"), 1); ## Compliant Solution (Type Interpretation Error) ## This compliant so...
## Risk Assessment Inconsistent typing in variadic functions can result in abnormal program termination or unintended information disclosure. Recommendation Severity Likelihood Detectable Repairable Priority Level DCL11-C High Probable Yes No P12 L1 Automated Detection Tool Version Checker Description CertC-DCL11 LANG....
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,098
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152098
3
2
DCL12-C
Implement abstract data types using opaque types
Abstract data types are not restricted to object-oriented languages such as C++ and Java. They should be created and used in C language programs as well. Abstract data types are most effective when used with private (opaque) data types and information hiding.
struct string_mx { size_t size; size_t maxsize; unsigned char strtype; char *cstr; }; typedef struct string_mx string_mx; /* Function declarations */ extern errno_t strcpy_m(string_mx *s1, const string_mx *s2); extern errno_t strcat_m(string_mx *s1, const string_mx *s2); /* ... */ ## Noncompliant Code Exampl...
struct string_mx; typedef struct string_mx string_mx; /* Function declarations */ extern errno_t strcpy_m(string_mx *s1, const string_mx *s2); extern errno_t strcat_m(string_mx *s1, const string_mx *s2); /* ... */ struct string_mx { size_t size; size_t maxsize; unsigned char strtype; char *cstr; }; ## Compli...
## Risk Assessment The use of opaque abstract data types, though not essential to secure programming, can significantly reduce the number of defects and vulnerabilities introduced in code, particularly during ongoing maintenance. Recommendation Severity Likelihood Detectable Repairable Priority Level DCL12-C Low Unlike...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,301
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152301
3
2
DCL13-C
Declare function parameters that are pointers to values not changed by the function as const
Declaring function parameters const indicates that the function promises not to change these values. In C, function arguments are passed by value rather than by reference. Although a function may change the values passed in, these changed values are discarded once the function returns. For this reason, many programmers...
void foo(int *x) { if (x != NULL) { *x = 3; /* Visible outside function */ } /* ... */ } void foo(const int *x) { if (x != NULL) { *x = 3; /* Compiler should generate diagnostic message */ } /* ... */ } char *strcat_nc(char *s1, char *s2); char *c_str1 = "c_str1"; const char *c_str2 = "c_str2"; c...
void foo(const int * x) { if (x != NULL) { printf("Value is %d\n", *x); } /* ... */ } char *strcat(char *s1, const char *s2); char *c_str1 = "c_str1"; const char *c_str2 = "c_str2"; char c_str3[9] = "c_str3"; const char c_str4[9] = "c_str4"; strcat(c_str3, c_str2); /* Args reversed to prevent overwritin...
## Risk Assessment Failing to declare an unchanging value const prohibits the function from working with values already cast as const . This problem can be sidestepped by type casting away the const , but doing so violates . Recommendation Severity Likelihood Detectable Repairable Priority Level DCL13-C Low Unlikely Ye...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,278
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152278
3
2
DCL15-C
Declare file-scope objects or functions that do not need external linkage as static
If a file-scope object or a function does not need to be visible outside of the file, it should be hidden by being declared as static . This practice creates more modular code and limits pollution of the global name space. Subclause 6.2.2 of the C Standard [ ISO/IEC 9899:2011 ] states: If the declaration of a file scop...
enum { MAX = 100 }; int helper(int i) { /* Perform some computation based on i */ } int main(void) { size_t i; int out[MAX]; for (i = 0; i < MAX; i++) { out[i] = helper(i); } /* ... */ } ## Noncompliant Code Example ## This noncompliant code example includes ahelper()function that is implicitly de...
enum {MAX = 100}; static int helper(int i) { /* Perform some computation based on i */ } int main(void) { size_t i; int out[MAX]; for (i = 0; i < MAX; i++) { out[i] = helper(i); } /* ... */ } ## Compliant Solution ## This compliant solution declareshelper()to have internal linkage, thereby prevent...
## Risk Assessment Allowing too many objects to have external linkage can use up descriptive identifiers, leading to more complicated identifiers, violations of abstraction models, and possible name conflicts with libraries. If the compilation unit implements a data abstraction, it may also expose invocations of privat...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,241
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152241
3
2
DCL16-C
Use "L," not "l," to indicate a long value
Lowercase letter l (ell) can easily be confused with the digit 1 (one). This can be particularly confusing when indicating that an integer literal constant is a long value. This recommendation is similar to . Likewise, you should use uppercase LL rather than lowercase ll when indicating that an integer literal constant...
printf("Sum is %ld\n", 1111 + 111l); ## Noncompliant Code Example This noncompliant example highlights the result of adding an integer and a long value even though it appears that two integers 1111 are being added: #FFCCCC c printf("Sum is %ld\n", 1111 + 111l);
printf("Sum is %ld\n", 1111 + 111L); ## Compliant Solution ## The compliant solution improvises by using an uppercaseLinstead of lowercaselto disambiguate the visual appearance: #ccccff c printf("Sum is %ld\n", 1111 + 111L);
## Risk Assessment Confusing a lowercase letter l (ell) with a digit 1 (one) when indicating that an integer denotation is a long value could lead to an incorrect value being written into code. Recommendation Severity Likelihood Detectable Repairable Priority Level DCL16-C Low Unlikely Yes Yes P3 L3 Automated Detection...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,269
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152269
3
2
DCL17-C
Beware of miscompiled volatile-qualified variables
As described in depth in rule , a volatile -qualified variable "shall be evaluated strictly according to the rules of the abstract machine" [ ISO/IEC 9899:2011 ]. In other words, the volatile qualifier is used to instruct the compiler to not make caching optimizations about a variable. However, as demonstrated in "Vola...
const volatile int x; volatile int y; void foo(void) { for(y = 0; y < 10; y++) { int z = x; } } foo: movl $0, y movl x, %eax jmp .L2 .L3: movl y, %eax incl %eax movl %eax, y .L2: movl y, %eax cmpl $10, %eax jg .L3 ret ## Noncompliant Code Example As demonstrated in Eide and Regehr's work, ...
int vol_read_int(volatile int *vp) { return *vp; } volatile int *vol_id_int(volatile int *vp) { return vp; } const volatile int x; volatile int y; void foo(void) { for(*vol_id_int(&y) = 0; vol_read_int(&y) < 10; *vol_id_int(&y) = vol_read_int(&y) + 1) { int z = vol_read_int(&x); } } ## Compliant Solution ...
## Risk Assessment The volatile qualifier should be used with caution in mission-critical situations. Always make sure code that assumes certain behavior when using the volatile qualifier is inspected at the object code level for compiler bugs. Rule Severity Likelihood Detectable Repairable Priority Level DCL17-C Mediu...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,234
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152234
3
2
DCL18-C
Do not begin integer constants with 0 when specifying a decimal value
The C Standard defines octal constants as a 0 followed by octal digits (0 1 2 3 4 5 6 7). Programming errors can occur when decimal values are mistakenly specified as octal constants.
i_array[0] = 2719; i_array[1] = 4435; i_array[2] = 0042; ## Noncompliant Code Example In this noncompliant code example, a decimal constant is mistakenly prefaced with zeros so that all the constants are a fixed length: #FFCCCC c i_array[0] = 2719; i_array[1] = 4435; i_array[2] = 0042; Although it may appear that i_ar...
i_array[0] = 2719; i_array[1] = 4435; i_array[2] = 42; ## Compliant Solution To avoid using wrong values and to make the code more readable, do not preface constants with zeroes if the value is meant to be decimal: #CCCCFF c i_array[0] = 2719; i_array[1] = 4435; i_array[2] = 42;
## Risk Assessment Misrepresenting decimal values as octal can lead to incorrect comparisons and assignments. Rule Severity Likelihood Detectable Repairable Priority Level DCL18-C Low Unlikely No No P1 L3 Automated Detection Tool Version Checker Description octal-constant Fully checked CertC-DCL18 LANG.TYPE.OC Octal co...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,335
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152335
3
2
DCL19-C
Minimize the scope of variables and functions
Variables and functions should be declared in the minimum scope from which all references to the identifier are still possible. When a larger scope than necessary is used, code becomes less readable, harder to maintain, and more likely to reference unintended variables (see ).
unsigned int count = 0; void counter() { if (count++ > MAX_COUNT) return; /* ... */ } size_t i = 0; for (i=0; i < 10; i++){ /* Perform operations */ } int f(int i) { /* Function definition */ } int g(int i) { int j = f(i); /* ... */ } ## Noncompliant Code Example In this noncompliant code example, t...
void counter() { static unsigned int count = 0; if (count++ > MAX_COUNT) return; /* ... */ } for (size_t i=0; i < 10; i++) { /* Perform operations */ } static int f(int i) { /* Function definition */ } int g(int i) { int j = f(i); /* ... */ } ## Compliant Solution In this compliant solution, the var...
## Risk Assessment Failure to minimize scope could result in less reliable, readable, and reusable code. Recommendation Severity Likelihood Detectable Repairable Priority Level DCL19-C Low Unlikely Yes Yes P3 L3 Automated Detection Tool Version Checker Description local-object-scope global-object-scope Partially checke...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,311
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152311
3
2
DCL20-C
Explicitly specify void when a function accepts no arguments
According to the C Standard, subclause 6.7.6.3, paragraph 14 [ ISO/IEC 9899:2011 ], An identifier list declares only the identifiers of the parameters of the function. An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters. The empty list in a ...
/* In foo.h */ void foo(); /* In foo.c */ void foo() { int i = 3; printf("i value: %d\n", i); } /* In caller.c */ #include "foo.h" foo(3); /* Compile using gcc4.3.3 */ void foo() { /* * Use assembly code to retrieve i * implicitly from caller * and transfer it to a less privileged file.  */ } ......
/* In foo.h */ void foo(void); /* In foo.c */ void foo(void) { int i = 3; printf("i value: %d\n", i); } /* In caller.c */ #include "foo.h" foo(3); void foo(void) { int i = 3; printf("i value: %d\n", i); } ## Compliant Solution (Ambiguous Interface) ## In this compliant solution,voidis specified explicitly ...
## Risk Assessment Recommendation Severity Likelihood Detectable Repairable Priority Level DCL20-C Medium Probable Yes Yes P12 L1 Automated Detection Tool Version Checker Description empty-parameter-list Fully checked CertC-DCL20 LANG.FUNCS.PROT Incomplete function prototype C3001, C3007 MISRA.FUNC.NO_PARAMS LDRA tool ...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,320
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152320
3
2
DCL21-C
Understand the storage of compound literals
Subclause 6.5.2.5 of the C Standard [ ISO/IEC 9899:2011 ] defines a compound literal as A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers. . . . The value of the compound literal is that of an unnamed object initiated by the initializer list. The storage f...
#include <stdio.h> typedef struct int_struct { int x; } int_struct; #define MAX_INTS 10 int main(void){ size_t i; int_struct *ints[MAX_INTS]; for (i = 0; i < MAX_INTS; i++) { ints[i] = &(int_struct){i}; } for (i = 0; i < MAX_INTS; i++) { printf("%d\n", ints[i]->x); }   return 0; } ## Nonco...
#include <stdio.h> typedef struct int_struct { int x; } int_struct; #define MAX_INTS 10 int main(void){ size_t i; int_struct ints[MAX_INTS]; for (i = 0; i < MAX_INTS; i++) { ints[i] = (int_struct){i}; } for (i = 0; i < MAX_INTS; i++) { printf("%d\n", ints[i].x); }   return 0; } ## Complian...
## Risk Assessment Recommendation Severity Likelihood Detectable Repairable Priority Level DCL21-C Low Unlikely No No P1 L3 Automated Detection Tool Version Checker Description Supported. Astrée reports runtime errors resulting from the misuse of compound literals. CertC-DCL21 C1054, C3217
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,049
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152049
3
2
DCL22-C
Use volatile for data that cannot be cached
An object that has volatile-qualified type may be modified in ways unknown to the implementation or have other unknown side effects. Asynchronous signal handling, for example, may cause objects to be modified in a manner unknown to the compiler. Without this type qualifier, unintended optimizations may occur. These opt...
#include <stddef.h> #include <stdint.h> extern void get_register_bank(int32_t **bank, size_t *num_registers); extern void external_wait(void); void func(void) { int32_t bank[3]; size_t num_regs = 3; get_register_bank((int32_t **)&bank, &num_regs); if (num_regs < 3) { /* Hand...
#include <stddef.h> #include <stdint.h> extern void get_register_bank(volatile int32_t **bank, size_t *num_registers); extern void external_wait(void); void func(void) { volatile int32_t bank[3]; size_t num_regs = 3; get_register_bank((volatile int32_t **)&bank, &num_regs); if (...
## Risk Assessment Failure to declare variables containing data that cannot be cached as volatile can result in unexpected runtime behavior resulting from compiler optimizations. Recommendation Severity Likelihood Detectable Repairable Priority Level DCL22-C Low Probable No Yes P4 L3 Automated Detection Tool Version Ch...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,406
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152406
3
2
DCL23-C
Guarantee that mutually visible identifiers are unique
According to subclause 6.2.7 of the C Standard [ ISO/IEC 9899:2011 ], All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined. (See also undefined behavior 14 of Annex J.) Further, according to subclause 6.4.2.1, Any identifiers that differ in a signif...
extern int *global_symbol_definition_lookup_table_a; extern int *global_symbol_definition_lookup_table_b; extern int *\U00010401\U00010401\U00010401\U00010401; extern int *\U00010401\U00010401\U00010401\U00010402; ## Noncompliant Code Example (Source Character Set) On implementations that support only the minimum req...
extern int *a_global_symbol_definition_lookup_table; extern int *b_global_symbol_definition_lookup_table; extern int *\U00010401\U00010401\U00010401\U00010401; extern int *\U00010402\U00010401\U00010401\U00010401; ## Compliant Solution (Source Character Set) ## In a compliant solution, the significant characters in e...
## Risk Assessment Nonunique identifiers can lead to abnormal program termination, denial-of-service attacks, or unintended information disclosure. Rule Severity Likelihood Detectable Repairable Priority Level DCL23-C Medium Unlikely Yes Yes P6 L2 Automated Detection Tool Version Checker Description Supported indirectl...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 02. Declarations and Initialization (DCL)
c
87,152,466
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152466
2
2
DCL30-C
Declare objects with appropriate storage durations
Every object has a storage duration that determines its lifetime: static , thread , automatic , or allocated . According to the C Standard, 6.2.4, paragraph 2 [ ISO/IEC 9899:2024 ], The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, ...
#include <stdio.h>   const char *p; void dont_do_this(void) { const char c_str[] = "This will change"; p = c_str; /* Dangerous */ } void innocuous(void) { printf("%s\n", p); } int main(void) { dont_do_this(); innocuous(); return 0; } char *init_array(void) { char array[10]; /* Initialize array */ r...
void this_is_OK(void) { const char c_str[] = "Everything OK"; const char *p = c_str; /* ... */ } /* p is inaccessible outside the scope of string c_str */ const char *p; void is_this_OK(void) { const char c_str[] = "Everything OK?"; p = c_str; /* ... */ p = NULL; } #include <stddef.h> void init_array(ch...
## Risk Assessment Referencing an object outside of its lifetime can result in an attacker being able to execute arbitrary code. Rule Severity Likelihood Detectable Repairable Priority Level DCL30-C High Probable No No P6 L2 Automated Detection Tool Version Checker Description pointered-deallocation return-reference-lo...
SEI CERT C Coding Standard > 2 Rules > Rule 02. Declarations and Initialization (DCL)
c
87,152,112
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152112
2
2
DCL31-C
Declare identifiers before using them
The C23 Standard requires type specifiers and forbids implicit function declarations. The C90 Standard allows implicit typing of variables and functions. Consequently, some existing legacy code uses implicit typing. Some C compilers still support legacy code by allowing implicit typing, but it should not be used for ne...
extern foo; #include <stddef.h> /* #include <stdlib.h> is missing */ int main(void) { for (size_t i = 0; i < 100; ++i) { /* int malloc() assumed */ char *ptr = (char *)malloc(0x10000000); *ptr = 'a'; } return 0; } #include <limits.h> #include <stdio.h>   foo(void) { return UINT_MAX; } int main(...
extern int foo; #include <stdlib.h> int main(void) { for (size_t i = 0; i < 100; ++i) { char *ptr = (char *)malloc(0x10000000); *ptr = 'a'; } return 0; } #include <limits.h> #include <stdio.h> unsigned int foo(void) { return UINT_MAX; } int main(void) { long long int c = foo(); printf("%lld\n"...
## Risk Assessment Because implicit declarations lead to less stringent type checking, they can introduce unexpected and erroneous behavior. Occurrences of an omitted type specifier in existing code are rare, and the consequences are generally minor, perhaps resulting in abnormal program termination . Rule Severity Lik...
SEI CERT C Coding Standard > 2 Rules > Rule 02. Declarations and Initialization (DCL)
c
87,152,132
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152132
2
2
DCL36-C
Do not declare an identifier with conflicting linkage classifications
Linkage can make an identifier declared in different scopes or declared multiple times within the same scope refer to the same object or function. Identifiers are classified as externally linked , internally linked , or not linked . These three kinds of linkage have the following characteristics [ Kirch-Prinz 2002 ]: E...
int i1 = 10; /* Definition, external linkage */ static int i2 = 20; /* Definition, internal linkage */ extern int i3 = 30; /* Definition, external linkage */ int i4; /* Tentative definition, external linkage */ static int i5; /* Tentative definition, internal linkage */ int i1; /* Valid t...
int i1 = 10; /* Definition, external linkage */ static int i2 = 20; /* Definition, internal linkage */ extern int i3 = 30; /* Definition, external linkage */ int i4; /* Tentative definition, external linkage */ static int i5; /* Tentative definition, internal linkage */ int main(void) { ...
## Risk Assessment Use of an identifier classified as both internally and externally linked is undefined behavior 8 . Rule Severity Likelihood Detectable Repairable Priority Level DCL36-C Medium Probable Yes No P8 L2 Automated Detection Tool Version Checker Description static-function-declaration static-object-declarat...
SEI CERT C Coding Standard > 2 Rules > Rule 02. Declarations and Initialization (DCL)
c
87,152,308
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152308
2
2
DCL37-C
Do not declare or define a reserved identifier
According to the C Standard, 6.4.2.1 paragraph 7 [ ISO/IEC 9899:2024 ], Some identifiers are reserved. —  All identifiers that begin with a double underscore ( __ ) or begin with an underscore ( _ ) followed by an uppercase letter are reserved for any use, except those identifiers which are lexically identical to keywo...
#ifndef _MY_HEADER_H_ #define _MY_HEADER_H_ /* Contents of <my_header.h> */ #endif /* _MY_HEADER_H_ */ #include <stddef.h> static const size_t _max_limit = 1024; size_t _limit = 100; unsigned int getValue(unsigned int count) { return count < _limit ? count : _limit; } #include <inttypes.h> #include <stdio.h> s...
#ifndef MY_HEADER_H #define MY_HEADER_H /* Contents of <my_header.h> */ #endif /* MY_HEADER_H */ #include <stddef.h> static const size_t max_limit = 1024; size_t limit = 100; unsigned int getValue(unsigned int count) { return count < limit ? count : limit; } #include <inttypes.h> #include <stdio.h>   static con...
## Risk Assessment Using reserved identifiers can lead to incorrect program operation. Rule Severity Likelihood Detectable Repairable Priority Level DCL37-C Low Unlikely Yes No P2 L3 Automated Detection Tool Version Checker Description future-library-use language-override reserved-declaration reserved-identifier langua...
SEI CERT C Coding Standard > 2 Rules > Rule 02. Declarations and Initialization (DCL)
c
87,152,410
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152410
2
2
DCL38-C
Use the correct syntax when declaring a flexible array member
Flexible array members are a special type of array in which the last element of a structure with more than one named member has an incomplete array type; that is, the size of the array is not specified explicitly within the structure. This "struct hack" was widely used in practice and supported by a variety of compiler...
#include <stdlib.h>   struct flexArrayStruct { int num; int data[1]; }; void func(size_t array_size) { /* Space is allocated for the struct */ struct flexArrayStruct *structP = (struct flexArrayStruct *) malloc(sizeof(struct flexArrayStruct) + sizeof(int) * (array_size - 1)); if (structP =...
#include <stdlib.h>   struct flexArrayStruct{ int num; int data[]; }; void func(size_t array_size) { /* Space is allocated for the struct */ struct flexArrayStruct *structP = (struct flexArrayStruct *) malloc(sizeof(struct flexArrayStruct) + sizeof(int) * array_size); if (structP == NULL) ...
## Risk Assessment Failing to use the correct syntax when declaring a flexible array member can result in undefined behavior 59 , although the incorrect syntax will work on most implementations. Rule Severity Likelihood Detectable Repairable Priority Level DCL38-C Low Unlikely Yes Yes P3 L3 Automated Detection Tool Ver...
SEI CERT C Coding Standard > 2 Rules > Rule 02. Declarations and Initialization (DCL)
c
87,151,978
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151978
2
2
DCL39-C
Avoid information leakage when passing a structure across a trust boundary
The C Standard, 6.7.3.2, discusses the layout of structure fields. It specifies that non-bit-field members are aligned in an implementation-defined manner and that there may be padding within or at the end of a structure. Furthermore, initializing the members of the structure does not guarantee initialization of the pa...
#include <stddef.h> struct test { int a; char b; int c; }; /* Safely copy bytes to user space */ extern int copy_to_user(void *dest, void *src, size_t size); void do_stuff(void *usr_buf) { struct test arg = {.a = 1, .b = 2, .c = 3}; copy_to_user(usr_buf, &arg, sizeof(arg)); } #include <string.h> struct t...
#include <stddef.h> #include <string.h>   struct test {   int a;   char b;   int c; };   /* Safely copy bytes to user space */ extern int copy_to_user(void *dest, void *src, size_t size);   void do_stuff(void *usr_buf) {   struct test arg = {.a = 1, .b = 2, .c = 3};   /* May be larger than strictly needed */   unsigned...
## Risk Assessment Padding units might contain sensitive data because the C Standard allows any padding to take unspecified values . A pointer to such a structure could be passed to other functions, causing information leakage. Rule Severity Likelihood Detectable Repairable Priority Level DCL39-C Low Unlikely No Yes P2...
SEI CERT C Coding Standard > 2 Rules > Rule 02. Declarations and Initialization (DCL)
c
87,151,998
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151998
2
2
DCL40-C
Do not create incompatible declarations of the same function or object
Two or more incompatible declarations of the same function or object must not appear in the same program because they result in undefined behavior . The C Standard, 6.2.7, mentions that two types may be distinct yet compatible and addresses precisely when two distinct types are compatible. The C Standard identifies fou...
/* In a.c */ extern int i; /* UB 14 */ int f(void) { return ++i; /* UB 36 */ } /* In b.c */ short i; /* UB 14 */ /* In a.c */ extern int *a; /* UB 14 */ int f(unsigned int i, int x) { int tmp = a[i]; /* UB 36: read access */ a[i] = x; /* UB 36: write access */ return tmp; } /* In b.c */ i...
/* In a.c */ extern int i; int f(void) { return ++i; } /* In b.c */ int i; /* In a.c */ extern int a[]; int f(unsigned int i, int x) { int tmp = a[i]; a[i] = x; return tmp; } /* In b.c */ int a[] = { 1, 2, 3, 4 }; /* In a.c */ extern int f(int a); int g(int a) { return f(a)...
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level DCL40-C Low Unlikely Yes No P2 L3
SEI CERT C Coding Standard > 2 Rules > Rule 02. Declarations and Initialization (DCL)
c
87,152,307
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152307
2
2
DCL41-C
Do not declare variables inside a switch statement before the first case label
According to the C Standard, 6.8.5.3, paragraph 4 [ ISO/IEC 9899:2024 ], A switch statement causes control to jump to, into, or past the statement that is the switch body , depending on the value of a controlling expression, and on the presence of a default label and the values of any case labels on or in the switch bo...
#include <stdio.h>   extern void f(int i);   void func(int expr) { switch (expr) { int i = 4; f(i); case 0: i = 17; /* Falls through into default code */ default: printf("%d\n", i); } } ## Noncompliant Code Example This noncompliant code example declares variables and contains executable st...
#include <stdio.h>   extern void f(int i);   int func(int expr) { /* * Move the code outside the switch block; now the statements * will get executed.  */ int i = 4; f(i); switch (expr) { case 0: i = 17; /* Falls through into default code */ default: printf("%d\n", i); } r...
## Risk Assessment Using test conditions or initializing variables before the first case statement in a switch block can result in unexpected behavior and undefined behavior 20 . Rule Severity Likelihood Detectable Repairable Priority Level DCL41-C Medium Unlikely Yes Yes P6 L2
SEI CERT C Coding Standard > 2 Rules > Rule 02. Declarations and Initialization (DCL)
c
87,152,092
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152092
3
10
ENV01-C
Do not make assumptions about the size of an environment variable
Do not make any assumptions about the size of environment variables because an adversary might have full control over the environment. If the environment variable needs to be stored, the length of the associated string should be calculated and the storage dynamically allocated (see ).
void f() { char path[PATH_MAX]; /* Requires PATH_MAX to be defined */ strcpy(path, getenv("PATH")); /* Use path */ } ## Noncompliant Code Example ## This noncompliant code example copies the string returned bygetenv()into a fixed-size buffer: #FFcccc c void f() { char path[PATH_MAX]; /* Requires PATH_MAX to be d...
void f() { char *path = NULL; /* Avoid assuming $PATH is defined or has limited length */ const char *temp = getenv("PATH"); if (temp != NULL) { path = (char*) malloc(strlen(temp) + 1); if (path == NULL) { /* Handle error condition */ } else { strcpy(path, temp); } /* Use path */...
## Risk Assessment Making assumptions about the size of an environmental variable can result in a buffer overflow. Recommendation Severity Likelihood Detectable Repairable Priority Level ENV01-C High Likely No No P9 L2 Automated Detection Tool Version Checker Description LANG.MEM.BO LANG.MEM.TO (general) Buffer overrun...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 10. Environment (ENV)
c
87,152,358
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152358
3
10
ENV02-C
Beware of multiple environment variables with the same effective name
The getenv() function searches an environment list for a string that matches a specified name and returns a pointer to a string associated with the matched list member. Subclause 7.22.4.6 of the C Standard [ ISO/IEC 9899:2011 ] states: The set of environment names and the method for altering the environment list are im...
if (putenv("TEST_ENV=foo") != 0) { /* Handle error */ } if (putenv("Test_ENV=bar") != 0) { /* Handle error */ } const char *temp = getenv("TEST_ENV"); if (temp == NULL) { /* Handle error */ } printf("%s\n", temp); foo bar ## Noncompliant Code Example ## This noncompliant code example behaves differently whe...
if (putenv("TEST_ENV=foo") != 0) { /* Handle error */ } if (putenv("OTHER_ENV=bar") != 0) { /* Handle error */ } const char *temp = getenv("TEST_ENV"); if (temp == NULL) { /* Handle error */ } printf("%s\n", temp); ## Compliant Solution Portable code should use environment variables that differ by more than c...
## Risk Assessment An attacker can create multiple environment variables with the same name (for example, by using the POSIX execve() function). If the program checks one copy but uses another, security checks may be circumvented. Recommendation Severity Likelihood Detectable Repairable Priority Level ENV02-C Low Unlik...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 10. Environment (ENV)
c
87,152,420
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152420
3
10
ENV03-C
Sanitize the environment when invoking external programs
Many programs and libraries, including the shared library loader on both UNIX and Windows systems, depend on environment variable settings. Because environment variables are inherited from the parent process when a program is executed, an attacker can easily sabotage variables, causing a program to behave in an unexpec...
if (system("/bin/ls dir.`date +%Y%m%d`") == -1) { /* Handle error */ } ## Noncompliant Code Example (POSIX,ls) This noncompliant code example invokes the C system() function to execute the /bin/ls program. The system() function passes a string to the command processor in the host environment to be executed. #ffcccc ...
char *pathbuf; size_t n; if (clearenv() != 0) { /* Handle error */ } n = confstr(_CS_PATH, NULL, 0); if (n == 0) { /* Handle error */ } if ((pathbuf = malloc(n)) == NULL) { /* Handle error */ } if (confstr(_CS_PATH, pathbuf, n) == 0) { /* Handle error */ } if (setenv("PATH", pathbuf, 1) == -1) { /* Handl...
## Risk Assessment Invoking an external program in an attacker-controlled environment is inherently dangerous. Recommendation Severity Likelihood Detectable Repairable Priority Level ENV03-C High Likely No No P9 L2 Automated Detection Tool Version Checker Description C5017 LDRA tool suite 588 S Partially implemented Re...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 10. Environment (ENV)
c
87,152,111
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152111
2
10
ENV30-C
Do not modify the object referenced by the return value of certain functions
Some functions return a pointer to an object that cannot be modified without causing undefined behavior . These functions include getenv() , setlocale() , localeconv() , asctime() , and strerror() . In such cases, the function call results must be treated as being const -qualified. The C Standard, 7.24.4.6, paragraph 4...
#include <stdlib.h>   void trstr(char *c_str, char orig, char rep) { while (*c_str != '\0') { if (*c_str == orig) { *c_str = rep; } ++c_str; } } void func(void) { char *env = getenv("TEST_ENV"); if (env == NULL) { /* Handle error */ } trstr(env,'"', '_'); } #include <locale.h>   void...
#include <stdlib.h> #include <string.h>   void trstr(char *c_str, char orig, char rep) { while (*c_str != '\0') { if (*c_str == orig) { *c_str = rep; } ++c_str; } }   void func(void) { const char *env; char *copy_of_env; env = getenv("TEST_ENV"); if (env == NULL) { /* Handle error */ ...
## Risk Assessment Modifying the object pointed to by the return value of getenv() , setlocale() , localeconv() , asctime() , or strerror() is undefined behavior . Even if the modification succeeds, the modified object can be overwritten by a subsequent call to the same function. Rule Severity Likelihood Detectable Rep...
SEI CERT C Coding Standard > 2 Rules > Rule 10. Environment (ENV)
c
87,152,100
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152100
2
10
ENV31-C
Do not rely on an environment pointer following an operation that may invalidate it
Some implementations provide a nonportable environment pointer that is valid when main() is called but may be invalidated by operations that modify the environment. The C Standard, J.5.2 [ ISO/IEC 9899:2024 ], states In a hosted environment, the main function receives a third argument, char * envp [] , that points to a...
#include <stdio.h> #include <stdlib.h>   int main(int argc, const char *argv[], const char *envp[]) { if (setenv("MY_NEW_VAR", "new_value", 1) != 0) { /* Handle error */ } if (envp != NULL) { for (size_t i = 0; envp[i] != NULL; ++i) { puts(envp[i]); } } return 0; } #include <stdio.h> #inclu...
#include <stdio.h> #include <stdlib.h>   extern char **environ; int main(void) { if (setenv("MY_NEW_VAR", "new_value", 1) != 0) { /* Handle error */ } if (environ != NULL) { for (size_t i = 0; environ[i] != NULL; ++i) { puts(environ[i]); } } return 0; } #include <stdio.h> #include <stdlib....
## Risk Assessment Using the envp environment pointer after the environment has been modified can result in undefined behavior . Rule Severity Likelihood Detectable Repairable Priority Level ENV31-C Low Probable Yes No P4 L3 Automated Detection Tool Version Checker Description invalidated-system-pointer-use Partially c...
SEI CERT C Coding Standard > 2 Rules > Rule 10. Environment (ENV)
c
87,152,169
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152169
2
10
ENV32-C
All exit handlers must return normally
The C Standard provides three functions that cause an application to terminate normally: _Exit() , exit() , and quick_exit() . These are collectively called exit functions . When the exit() function is called, or control transfers out of the main() entry point function, functions registered with atexit() are called (bu...
#include <stdlib.h> void exit1(void) { /* ... Cleanup code ... */ return; }   void exit2(void) { extern int some_condition; if (some_condition) { /* ... More cleanup code ... */ exit(0); } return; } int main(void) { if (atexit(exit1) != 0) { /* Handle error */ } if (atexit(exit2) != 0) {...
#include <stdlib.h> void exit1(void) { /* ... Cleanup code ... */ return; }   void exit2(void) { extern int some_condition; if (some_condition) { /* ... More cleanup code ... */ } return; } int main(void) { if (atexit(exit1) != 0) { /* Handle error */ } if (atexit(exit2) != 0) { /* Handl...
## Risk Assessment Terminating a call to an exit handler in any way other than by returning is undefined behavior and may result in abnormal program termination or other unpredictable behavior. It may also prevent other registered handlers from being invoked. Rule Severity Likelihood Detectable Repairable Priority Leve...
SEI CERT C Coding Standard > 2 Rules > Rule 10. Environment (ENV)
c
87,152,177
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152177
2
10
ENV33-C
Do not call system()
The C Standard system() function executes a specified command by invoking an implementation-defined command processor, such as a UNIX shell or CMD.EXE in Microsoft Windows. The POSIX popen() and Windows _popen() functions also invoke a command processor but create a pipe between the calling program and the executed com...
#include <string.h> #include <stdlib.h> #include <stdio.h> enum { BUFFERSIZE = 512 }; void func(const char *input) { char cmdbuf[BUFFERSIZE]; int len_wanted = snprintf(cmdbuf, BUFFERSIZE, "any_cmd '%s'", input); if (len_wanted >= BUFFERSIZE) { /* Handle error */ } else if (len_...
#include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <errno.h> #include <stdlib.h>   void func(char *input) { pid_t pid; int status; pid_t ret; char *const args[3] = {"any_exe", input, NULL}; char **env; extern char **environ; /* ... Sanitize arguments ... */ pid = fork(); if (p...
## Risk Assessments If the command string passed to system() , popen() , or other function that invokes a command processor is not fully sanitized , the risk of exploitation is high. In the worst case scenario, an attacker can execute arbitrary system commands on the compromised machine with the privileges of the vulne...
SEI CERT C Coding Standard > 2 Rules > Rule 10. Environment (ENV)
c
87,152,370
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152370
2
10
ENV34-C
Do not store pointers returned by certain functions
The C Standard, 7.24.4.6, paragraph 4 [ ISO/IEC 9899:2024 ], states The getenv function returns a pointer to a string associated with the matched list member. The string pointed to shall not be modified by the program but may be overwritten by a subsequent call to the getenv function. If the specified name cannot be fo...
#include <stdlib.h> #include <string.h> #include <stdio.h>   void func(void) { char *tmpvar; char *tempvar; tmpvar = getenv("TMP"); if (!tmpvar) { /* Handle error */ } tempvar = getenv("TEMP"); if (!tempvar) { /* Handle error */ } if (strcmp(tmpvar, tempvar) == 0) { printf("TMP and TEMP a...
#include <stdlib.h> #include <string.h> #include <stdio.h>   void func(void) { char *tmpvar; char *tempvar; const char *temp = getenv("TMP"); if (temp != NULL) { tmpvar = (char *)malloc(strlen(temp)+1); if (tmpvar != NULL) { strcpy(tmpvar, temp); } else { /* Handle error */ } } el...
## Risk Assessment Storing the pointer to the string returned by getenv() , localeconv() , setlocale() , or strerror() can result in overwritten data. Rule Severity Likelihood Detectable Repairable Priority Level ENV34-C Low Probable Yes No P4 L3 Related Vulnerabilities Search for vulnerabilities resulting from the vio...
SEI CERT C Coding Standard > 2 Rules > Rule 10. Environment (ENV)
c
87,152,349
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152349
3
12
ERR00-C
Adopt and implement a consistent and comprehensive error-handling policy
A secure system is invariably subject to stresses, such as those caused by attack, erroneous or malicious inputs, hardware or software faults, unanticipated user behavior, and unexpected environmental changes that are outside the bounds of "normal operation." Yet the system must continue to deliver essential services i...
null
null
## Risk Assessment Failure to adopt and implement a consistent and comprehensive error-handling policy is detrimental to system survivability and can result in a broad range of vulnerabilities depending on the operational characteristics of the system. Recommendation Severity Likelihood Detectable Repairable Priority L...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 12. Error Handling (ERR)
c
87,152,122
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152122
3
12
ERR01-C
Use ferror() rather than errno to check for FILE stream errors
Use ferror() rather than errno to check whether an error has occurred on a file stream (for example, after a long chain of stdio calls). The ferror() function tests the error indicator for a specified stream and returns nonzero if and only if the error indicator is set for the stream.
errno = 0; printf("This\n"); printf("is\n"); printf("a\n"); printf("test.\n"); if (errno != 0) { fprintf(stderr, "printf failed: %s\n", strerror(errno)); } ## Noncompliant Code Example Many implementations of the stdio package adjust their behavior slightly if stdout is a terminal. To make the determination, these i...
printf("This\n"); printf("is\n"); printf("a\n"); printf("test.\n"); if (ferror(stdout)) { fprintf(stderr, "printf failed\n"); } ## Compliant Solution This compliant solution uses ferror() to detect an error. In addition, if an early call to printf() fails, later calls may modify errno , whether they fail or not, so ...
## Risk Assessment Checking errno after multiple calls to library functions can lead to spurious error reporting, possibly resulting in incorrect program operation. Recommendation Severity Likelihood Detectable Repairable Priority Level ERR01-C Low Probable Yes Yes P6 L2 Automated Detection Tool Version Checker Descrip...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 12. Error Handling (ERR)
c
87,152,400
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152400
3
12
ERR02-C
Avoid in-band error indicators
Avoid in-band error indicators while designing interfaces. This practice is commonly used by C library functions but is not recommended. One example from the C Standard of a troublesome in-band error indicator is EOF (see ). Another problematic use of in-band error indicators from the C Standard involving the size_t an...
int i; ssize_t count = 0; for (i = 0; i < 9; ++i) { count += sprintf( buf + count, "%02x ", ((u8 *)&slreg_num)[i] ); } count += sprintf(buf + count, "\n"); ssize_t read(int fildes, void *buf, size_t nbyte); ## Noncompliant Code Example (sprintf()) ## This noncompliant code example is from the Linux Kernel Ma...
errno_t sprintf_m( string_m buf, const string_m fmt, int *count, ... ); int i; rsize_t count = 0; errno_t err; for (i = 0; i < 9; ++i) { err = sprintf_m( buf + count, "%02x ", &count, ((u8 *)&slreg_num)[i] ); if (err != 0) { /* Handle print error */ } } err = sprintf_m( buf + count, "%02x...
## Risk Assessment The risk in using in-band error indicators is difficult to quantify and is consequently given as low. However, if the use of in-band error indicators results in programmers' failing to check status codes or incorrectly checking them, the consequences can be more severe. Recommendation Severity Likeli...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 12. Error Handling (ERR)
c
87,152,110
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152110
3
12
ERR04-C
Choose an appropriate termination strategy
Some errors, such as out-of-range values, might be the result of erroneous user input. Interactive programs typically handle such errors by rejecting the input and prompting the user for an acceptable value. Servers reject invalid user input by indicating an error to the client while at the same time continuing to serv...
#include <stdlib.h> #include <stdio.h> int write_data(void) { const char *filename = "hello.txt"; FILE *f = fopen(filename, "w"); if (f == NULL) { /* Handle error */ } fprintf(f, "Hello, World\n"); /* ... */ abort(); /* Oops! Data might not be written! */ /* ... */ return 0; } int main(void) { ...
#include <stdlib.h> #include <stdio.h> int write_data(void) { const char *filename = "hello.txt"; FILE *f = fopen(filename, "w"); if (f == NULL) { /* Handle error */ } fprintf(f, "Hello, World\n"); /* ... */ exit(EXIT_FAILURE); /* Writes data and closes f */ /* ... */ return 0; } int main(void) ...
## Risk Assessment As an example, using abort() or _Exit() in place of exit() may leave written files in an inconsistent state and may also leave sensitive temporary files on the file system. Recommendation Severity Likelihood Detectable Repairable Priority Level ERR04-C Medium Probable No No P4 L3 Automated Detection ...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 12. Error Handling (ERR)
c
87,152,136
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152136
3
12
ERR05-C
Application-independent code should provide error detection without dictating error handling
Application-independent code includes code that is Shipped with the compiler or operating system From a third-party library Developed in-house When application-specific code detects an error, it can immediately respond with a specific action, as in if (something_really_bad_happens) { take_me_some_place_safe(); } This r...
void g(void) { /* ... */ if (something_really_bad_happens) { fprintf(stderr, "Something really bad happened!\n"); abort(); } /* ... */ } void f(void) { g(); /* ... Do the rest of f ... */ } ## Noncompliant Code Example This noncompliant code example consists of two application-independent function...
const errno_t ESOMETHINGREALLYBAD = 1; errno_t g(void) { /* ... */ if (something_really_bad_happens) { return ESOMETHINGREALLYBAD; } /* ... */ return 0; } errno_t f(void) { errno_t status = g(); if (status != 0) { return status; } /* ... Do the rest of f ... */ return 0; } const errno_t...
## Risk Assessment Lack of an error-detection mechanism prevents applications from knowing when an error has disrupted normal program behavior. Recommendation Severity Likelihood Detectable Repairable Priority Level ERR05-C Medium Probable Yes No P8 L2 Automated Detection Tool Version Checker Description Compass/ROSE C...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 12. Error Handling (ERR)
c
87,152,296
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152296
3
12
ERR06-C
Understand the termination behavior of assert() and abort()
The C Standard, subclause 7.2.1.1 [ ISO/IEC 9899:2011 ], defines assert() to have the following behavior: The assert macro puts diagnostic tests into programs; it expands to a void expression. When it is executed, if expression (which shall have a scalar type) is false (that is, compares equal to 0), the assert macro w...
void cleanup(void) { /* Delete temporary files, restore consistent state, etc. */ } int main(void) { if (atexit(cleanup) != 0) { /* Handle error */ } /* ... */ assert(/* Something bad didn't happen */); /* ... */ } ## Noncompliant Code Example ## This noncompliant code example defines a function th...
void cleanup(void) { /* Delete temporary files, restore consistent state, etc. */ } int main(void) { if (atexit(cleanup) != 0) { /* Handle error */ } /* ... */ if (/* Something bad happened */) { exit(EXIT_FAILURE); } /* ... */ } ## Compliant Solution In this compliant solution, the call to a...
## Risk Assessment Unsafe use of abort() may leave files written in an inconsistent state. It may also leave sensitive temporary files on the file system. Recommendation Severity Likelihood Detectable Repairable Priority Level ERR06-C Medium Unlikely No No P2 L3 Automated Detection Tool Version Checker Description bad-...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 12. Error Handling (ERR)
c
87,152,338
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152338
3
12
ERR07-C
Prefer functions that support error checking over equivalent functions that don't
When you have a choice of two functions to accomplish the same task, prefer the one with better error checking and reporting. The following table shows a list of C standard library functions that provide limited or no error checking and reporting along with preferable alternatives: Function Preferable Alternative Comme...
int si; if (argc > 1) { si = atoi(argv[1]); } char *file_name; FILE *fp; /* Initialize file_name */ fp = fopen(file_name, "r"); if (fp == NULL) { /* Handle open error */ } /* Read data */ rewind(fp); /* Continue */ FILE *file; /* Setup file */ setbuf(file, NULL); /* ... */ ## Noncompliant Code Example (ato...
long sl; int si; char *end_ptr; if (argc > 1) { errno = 0; sl = strtol(argv[1], &end_ptr, 10); if ((sl == LONG_MIN || sl == LONG_MAX) && errno != 0) { perror("strtol error"); } else if (end_ptr == argv[1]) { if (puts("error encountered during conversion") == EOF) { /* Handle error */ ...
## Risk Assessment Although it is rare for a violation of this rule to result in a security vulnerability , it can easily result in lost or misinterpreted data. Recommendation Severity Likelihood Detectable Repairable Priority Level ERR07-C Medium Probable Yes Yes P12 L1 Automated Detection This rule in general cannot ...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 12. Error Handling (ERR)
c
87,152,351
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152351
2
12
ERR30-C
Take care when reading errno
The value of errno is initialized to zero at program startup, but it is never subsequently set to zero by any C standard library function. The value of errno may be set to nonzero by a C standard library function call whether or not there is an error, provided the use of errno is not documented in the description of th...
#include <errno.h> #include <limits.h> #include <stdlib.h>   void func(const char *c_str) { unsigned long number; char *endptr; number = strtoul(c_str, &endptr, 0); if (endptr == c_str || (number == ULONG_MAX && errno == ERANGE)) { /* Handle error */ } else { /* Computatio...
#include <errno.h> #include <limits.h> #include <stdlib.h>   void func(const char *c_str) { unsigned long number; char *endptr;   errno = 0; number = strtoul(c_str, &endptr, 0); if (endptr == c_str || (number == ULONG_MAX && errno == ERANGE)) { /* Handle error */ } else { /...
## Risk Assessment The improper use of errno may result in failing to detect an error condition or in incorrectly identifying an error condition when none exists. Rule Severity Likelihood Detectable Repairable Priority Level ERR30-C Medium Probable Yes Yes P12 L1 Automated Detection Tool Version Checker Description cha...
SEI CERT C Coding Standard > 2 Rules > Rule 12. Error Handling (ERR)
c
87,152,125
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152125
2
12
ERR32-C
Do not rely on indeterminate values of errno
According to the C Standard Annex J.2 (133) [ ISO/IEC 9899:2024 ], the behavior of a program is undefined when the value of errno is referred to after a signal occurred other than as the result of calling the abort or raise function and the corresponding signal handler obtained a SIG_ERR return from a call to the signa...
#include <signal.h> #include <stdlib.h> #include <stdio.h> typedef void (*pfv)(int); void handler(int signum) { pfv old_handler = signal(signum, SIG_DFL); if (old_handler == SIG_ERR) { perror("SIGINT handler"); /* Undefined behavior */ /* Handle error */ } } int main(void) { pfv old_handler = signal(...
#include <signal.h> #include <stdlib.h> #include <stdio.h> typedef void (*pfv)(int); void handler(int signum) { pfv old_handler = signal(signum, SIG_DFL); if (old_handler == SIG_ERR) { abort(); } } int main(void) { pfv old_handler = signal(SIGINT, handler); if (old_handler == SIG_ERR) { perror("SIG...
## Risk Assessment Referencing indeterminate values of errno is undefined behavior . Rule Severity Likelihood Detectable Repairable Priority Level ERR32-C Low Unlikely Yes Yes P3 L3 Automated Detection Tool Version Checker Description Supported CertC-ERR32 Compass/ROSE Could detect violations of this rule by looking fo...
SEI CERT C Coding Standard > 2 Rules > Rule 12. Error Handling (ERR)
c
87,152,272
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152272
2
12
ERR33-C
Detect and handle standard library errors
The majority of the standard library functions, including I/O functions and memory allocation functions, return either a valid value or a value of the correct return type that indicates an error (for example, −1 or a null pointer). Assuming that all calls to such functions will succeed and failing to check the return v...
#include <locale.h> #include <stdlib.h>   int utf8_to_wcs(wchar_t *wcs, size_t n, const char *utf8, size_t *size) { if (NULL == size) { return -1; } setlocale(LC_CTYPE, "en_US.UTF-8"); *size = mbstowcs(wcs, utf8, n); return 0; } #include <stdlib.h> #include <string.h>   enum { SIG_DESC_SI...
#include <locale.h> #include <stdlib.h>   int utf8_to_wcs(wchar_t *wcs, size_t n, const char *utf8, size_t *size) { if (NULL == size) { return -1; } const char *save = setlocale(LC_CTYPE, "en_US.UTF-8"); if (NULL == save) { return -1; } *size = mbstowcs(wcs, utf8, n); if (NULL == ...
## Risk Assessment Failing to detect error conditions can lead to unpredictable results, including abnormal program termination and denial-of-service attacks or, in some situations, could even allow an attacker to run arbitrary code. Rule Severity Likelihood Detectable Repairable Priority Level ERR33-C High Likely Yes ...
SEI CERT C Coding Standard > 2 Rules > Rule 12. Error Handling (ERR)
c
87,152,395
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152395
2
12
ERR34-C
Detect errors when converting a string to a number
The process of parsing an integer or floating-point number from a string can produce many errors. The string might not contain a number. It might contain a number of the correct type that is out of range (such as an integer that is larger than INT_MAX ). The string may also contain extra information after the number, w...
#include <stdlib.h>   void func(const char *buff) { int si; if (buff) { si = atoi(buff); } else { /* Handle error */ } } atoi: (int)strtol(nptr, (char **)NULL, 10) atol: strtol(nptr, (char **)NULL, 10) atoll: strtoll(nptr, (char **)NULL, 10) atof: strtod(nptr, (char **)NULL) #include <stdio.h>   void...
#include <errno.h> #include <limits.h> #include <stdlib.h> #include <stdio.h>   void func(const char *buff) { char *end; int si; errno = 0; const long sl = strtol(buff, &end, 10); if (end == buff) { (void) fprintf(stderr, "%s: not a decimal number\n", buff); } else if ('\0' != *end) { (void) fpri...
## Risk Assessment It is rare for a violation of this rule to result in a security vulnerability unless it occurs in security-sensitive code. However, violations of this rule can easily result in lost or misinterpreted data. Recommendation Severity Likelihood Detectable Repairable Priority Level ERR34-C Medium Unlikely...
SEI CERT C Coding Standard > 2 Rules > Rule 12. Error Handling (ERR)
c
87,152,225
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152225
3
3
EXP00-C
Use parentheses for precedence of operation
C programmers commonly make errors regarding the precedence rules of C operators because of the unintuitive low-precedence levels of & , | , ^ , << , and >> . Mistakes regarding precedence rules can be avoided by the suitable use of parentheses. Using parentheses defensively reduces errors and, if not taken to excess, ...
x & 1 == 0 x & (1 == 0) (x & 0) ## Noncompliant Code Example ## The intent of the expression in this noncompliant code example is to test the least significant bit ofx: #FFCCCC c x & 1 == 0 Because of operator precedence rules, the expression is parsed as #FFCCCC c x & (1 == 0) which evaluates to #FFCCCC c (x & 0) a...
(x & 1) == 0 ## Compliant Solution ## In this compliant solution, parentheses are used to ensure the expression evaluates as expected: #ccccff c (x & 1) == 0
## Risk Assessment Mistakes regarding precedence rules may cause an expression to be evaluated in an unintended way, which can lead to unexpected and abnormal program behavior. Recommendation Severity Likelihood Detectable Repairable Priority Level EXP00-C Low Probable Yes Yes P6 L2 Automated Detection Tool Version Che...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP)
c
87,152,061
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152061
3
3
EXP02-C
Be aware of the short-circuit behavior of the logical AND and OR operators
The logical AND and logical OR operators ( && and || , respectively) exhibit "short-circuit" operation. That is, the second operand is not evaluated if the result can be deduced solely by evaluating the first operand. Programmers should exercise caution if the second operand contains side effects because it may not be ...
char *p = /* Initialize; may or may not be NULL */ if (p || (p = (char *) malloc(BUF_SIZE)) ) { /* Perform some computation based on p */ free(p); p = NULL; } else { /* Handle malloc() error */ return; } ## Noncompliant Code Example In this noncompliant code example, the second operand of the logical OR ope...
char *p = /* Initialize; may or may not be NULL */ char *q = NULL; if (p == NULL) { q = (char *) malloc(BUF_SIZE); p = q; } if (p == NULL) { /* Handle malloc() error */ return; } /* Perform some computation based on p */ free(q); q = NULL; ## Compliant Solution In this compliant solution, a second pointer, q ...
## Risk Assessment Failing to understand the short-circuit behavior of the logical OR or AND operator may cause unintended program behavior. Recommendation Severity Likelihood Detectable Repairable Priority Level EXP02-C Low Unlikely No No P1 L3 Automated Detection Tool Version Checker Description logop-side-effect Ful...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP)
c
87,152,053
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152053
3
3
EXP03-C
Do not assume the size of a structure is the sum of the sizes of its members
The size of a structure is not always equal to the sum of the sizes of its members. Subclause 6.7.2.1 of the C Standard states, "There may be unnamed padding within a structure object, but not at its beginning" [ ISO/IEC 9899:2011 ]. This unnamed padding is often called structure padding . Structure members are arrange...
enum { buffer_size = 50 }; struct buffer { size_t size; char bufferC[buffer_size]; }; /* ... */ void func(const struct buffer *buf) { /* * Incorrectly assumes sizeof(struct buffer) = * sizeof(size_t) + sizeof(bufferC)  */ struct buffer *buf_cpy = (struct buffer *)malloc( sizeof(size_t) + (buffer...
enum { buffer_size = 50 }; struct buffer { size_t size; char bufferC[buffer_size]; }; /* ... */ void func(const struct buffer *buf) { struct buffer *buf_cpy = (struct buffer *)malloc(sizeof(struct buffer)); if (buf_cpy == NULL) { /* Handle malloc() error */ } /* ... */ memcpy(buf_cpy, buf,...
## Risk Assessment Failure to correctly determine the size of a structure can lead to subtle logic errors and incorrect calculations, the effects of which can lead to abnormal program termination, memory corruption, or execution of arbitrary code. Recommendation Severity Likelihood Detectable Repairable Priority Level ...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP)
c
87,152,191
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152191
3
3
EXP05-C
Do not cast away a const qualification
Do not cast away a const qualification on an object of pointer type. Casting away the const qualification allows a program to modify the object referred to by the pointer, which may result in undefined behavior . See undefined behavior 61 in Appendix J of the C Standard. As an illustration, the C Standard [ ISO/IEC 989...
void remove_spaces(const char *str, size_t slen) { char *p = (char *)str; size_t i; for (i = 0; i < slen && str[i]; i++) { if (str[i] != ' ') *p++ = str[i]; } *p = '\0'; } const int vals[3] = {3, 4, 5}; memset(vals, 0, sizeof(vals)); ## Noncompliant Code Example The remove_spaces() function in this nonc...
void remove_spaces(char *str, size_t slen) { char *p = str; size_t i; for (i = 0; i < slen && str[i]; i++) { if (str[i] != ' ') *p++ = str[i]; } *p = '\0'; } int vals[3] = {3, 4, 5}; memset(vals, 0, sizeof(vals)); ## Compliant Solution In this compliant solution, the function remove_spaces() is passed a...
## Risk Assessment If the object is constant, the compiler may allocate storage in ROM or write-protected memory. Attempting to modify such an object may lead to a program crash or denial-of-service attack . Recommendation Severity Likelihood Detectable Repairable Priority Level EXP05-C Medium Probable No No P4 L3 Auto...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP)
c
87,152,149
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152149
3
3
EXP07-C
Do not diminish the benefits of constants by assuming their values in expressions
If a constant value is given for an identifier, do not diminish the maintainability of the code in which it is used by assuming its value in expressions. Simply giving the constant a name is not enough to ensure modifiability; you must be careful to always use the name, and remember that the value can change. This reco...
#include <stdio.h> /* ... */ nblocks = 1 + ((nbytes - 1) >> 9); /* BUFSIZ = 512 = 2^9 */ ## Noncompliant Code Example The header stdio.h defines the BUFSIZ macro, which expands to an integer constant expression that is the size of the buffer used by the setbuf() function. This noncompliant code example defeats the pur...
#include <stdio.h> /* ... */ nblocks = 1 + (nbytes - 1) / BUFSIZ; ## Compliant Solution ## This compliant solution uses the identifier assigned to the constant value in the expression: #ccccff c #include <stdio.h> /* ... */ nblocks = 1 + (nbytes - 1) / BUFSIZ; Most modern C compilers will optimize this code appropriat...
## Risk Assessment Assuming the value of an expression diminishes the maintainability of code and can produce unexpected behavior under any circumstances in which the constant changes. Recommendation Severity Likelihood Detectable Repairable Priority Level EXP07-C Low Unlikely No No P1 L3 Automated Detection Tool Versi...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP)
c
87,152,126
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152126
3
3
EXP08-C
Ensure pointer arithmetic is used correctly
When performing pointer arithmetic, the size of the value to add to a pointer is automatically scaled to the size of the type of the pointed-to object. For instance, when adding a value to the byte address of a 4-byte integer, the value is scaled by a factor of 4 and then added to the pointer. Failing to understand how...
int buf[INTBUFSIZE]; int *buf_ptr = buf; while (havedata() && buf_ptr < (buf + sizeof(buf))) { *buf_ptr++ = parseint(getdata()); } struct big { unsigned long long ull_1; /* Typically 8 bytes */ unsigned long long ull_2; /* Typically 8 bytes */ unsigned long long ull_3; /* Typically 8 bytes */ int si_4; /* T...
int buf[INTBUFSIZE]; int *buf_ptr = buf; while (havedata() && buf_ptr < (buf + INTBUFSIZE)) { *buf_ptr++ = parseint(getdata()); } int buf[INTBUFSIZE]; int *buf_ptr = buf; while (havedata() && buf_ptr < &buf[INTBUFSIZE]) { *buf_ptr++ = parseint(getdata()); } struct big { unsigned long long ull_1; /* Typically ...
## Risk Assessment Failure to understand and properly use pointer arithmetic can allow an attacker to execute arbitrary code. Recommendation Severity Likelihood Detectable Repairable Priority Level EXP08-C High Probable No No P6 L2 Automated Detection Tool Version Checker Description Supported: Astrée reports potential...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP)
c
87,152,073
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152073
3
3
EXP09-C
Use sizeof to determine the size of a type or variable
Do not hard code the size of a type into an application. Because of alignment, padding, and differences in basic types (e.g., 32-bit versus 64-bit pointers), the size of most types can vary between compilers and even versions of the same compiler. Using the sizeof operator to determine sizes improves the clarity of wha...
int f(void) { /* Assuming 32-bit pointer, 32-bit integer */ size_t i; int **matrix = (int **)calloc(100, 4); if (matrix == NULL) { return -1; /* Indicate calloc() failure */ } for (i = 0; i < 100; i++) { matrix[i] = (int *)calloc(i, 4); if (matrix[i] == NULL) { return -1; /* Indicate calloc...
int f(void) { size_t i; int **matrix = (int **)calloc(100, sizeof(*matrix)); if (matrix == NULL) { return -1; /* Indicate calloc() failure */ } for (i = 0; i < 100; i++) { matrix[i] = (int *)calloc(i, sizeof(**matrix)); if (matrix[i] == NULL) { return -1; /* Indicate calloc() failure */ ...
## Risk Assessment Porting code with hard-coded sizes can result in a buffer overflow or related vulnerability . Recommendation Severity Likelihood Detectable Repairable Priority Level EXP09-C High Unlikely No Yes P6 L2 Automated Detection Tool Version Checker Description alloc-without-sizeof Partially checked Compass/...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP)
c
87,152,207
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152207
3
3
EXP10-C
Do not depend on the order of evaluation of subexpressions or the order in which side effects take place
The order of evaluation of subexpressions and the order in which side effects take place are frequently defined as unspecified behavior by the C Standard. Counterintuitively, unspecified behavior in behavior for which the standard provides two or more possibilities and imposes no further requirements on which is chosen...
(*pf[f1()]) (f2(), f3() + f4()) #include <stdio.h> int g; int f(int i) { g = i; return i; } int main(void) { int x = f(1) + f(2); printf("g = %d\n", g); /* ... */ return 0; } ## Noncompliant Code Example The order of evaluation of the function designator, the actual arguments, and subexpressions within...
#include <stdio.h> int g; int f(int i) { g = i; return i; } int main(void) { int x = f(1); x += f(2); printf("g = %d\n", g); /* ... */ return 0; } ## Compliant Solution This compliant solution is independent of the order of evaluation of the operands and can be interpreted in only one way: #ccccff c ...
## Risk Assessment Recommendation Severity Likelihood Detectable Repairable Priority Level EXP10-C Medium Probable No Yes P8 L2 Automated Detection Tool Version Checker Description evaluation-order multiple-volatile-accesses Partially checked CertC-EXP10 Fully implemented LANG.STRUCT.SE.IOE Indeterminate Order of Evalu...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP)
c
87,152,352
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152352
3
3
EXP11-C
Do not make assumptions regarding the layout of structures with bit-fields
The internal representations of bit-field structures have several properties (such as internal padding) that are implementation-defined . Additionally, bit-field structures have several implementation-defined constraints: The alignment of bit-fields in the storage unit (for example, the bit-fields may be allocated from...
struct bf { unsigned int m1 : 8; unsigned int m2 : 8; unsigned int m3 : 8; unsigned int m4 : 8; }; /* 32 bits total */ m4 m3 m2 m1 m1 m2 m3 m4 struct bf { unsigned int m1 : 8; unsigned int m2 : 8; unsigned int m3 : 8; unsigned int m4 : 8; }; /* 32 bits total */ void function() { struct...
struct bf { unsigned int m1 : 8; unsigned int m2 : 8; unsigned int m3 : 8; unsigned int m4 : 8; }; /* 32 bits total */ void function() { struct bf data; data.m1 = 0; data.m2 = 0; data.m3 = 0; data.m4 = 0; data.m1++; } struct bf { unsigned int m1 : 6; unsigned int m2 : 4; }; void function() { ...
## Risk Assessment Making invalid assumptions about the type of type-cast data, especially bit-fields, can result in unexpected data values. Recommendation Severity Likelihood Detectable Repairable Priority Level EXP11-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Description Supported: Astrée ...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 03. Expressions (EXP)