Datasets:
language large_stringclasses 1
value | page_id int64 88M 88M | page_url large_stringlengths 73 73 | chapter int64 2 2 | section int64 1 49 | rule_id large_stringlengths 9 9 | title large_stringlengths 21 109 | intro large_stringlengths 321 6.96k | noncompliant_code large_stringlengths 468 8.03k | compliant_solution large_stringlengths 276 8.12k | risk_assessment large_stringlengths 116 1.67k ⌀ | breadcrumb large_stringclasses 11
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
cplusplus | 88,046,461 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046461 | 2 | 10 | CON50-CPP | Do not destroy a mutex while it is locked | Mutex objects are used to protect shared data from being concurrently accessed. If a mutex object is destroyed while a thread is blocked waiting for the lock,
critical sections
and shared data are no longer protected.
The C++ Standard, [thread.mutex.class], paragraph 5 [
ISO/IEC 14882-2014
], states the following:
The ... | #include <mutex>
#include <thread>
const size_t maxThreads = 10;
void do_work(size_t i, std::mutex *pm) {
std::lock_guard<std::mutex> lk(*pm);
// Access data protected by the lock.
}
void start_threads() {
std::thread threads[maxThreads];
std::mutex m;
for (size_t i = 0; i < maxThreads; ++i) {
thread... | #include <mutex>
#include <thread>
const size_t maxThreads = 10;
void do_work(size_t i, std::mutex *pm) {
std::lock_guard<std::mutex> lk(*pm);
// Access data protected by the lock.
}
std::mutex m;
void start_threads() {
std::thread threads[maxThreads];
for (size_t i = 0; i < maxThreads; ++i) {
threads... | ## Risk Assessment
Destroying a mutex while it is locked may result in invalid control flow and data corruption.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CON50-CPP
Medium
Probable
No
No
P4
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 10. Concurrency (CON) |
cplusplus | 88,046,430 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046430 | 2 | 10 | CON51-CPP | Ensure actively held locks are released on exceptional conditions | Mutexes that are used to protect accesses to shared data may be locked using the
lock()
member function and unlocked using the
unlock()
member function. If an exception occurs between the call to
lock()
and the call to
unlock()
, and the exception changes control flow such that
unlock()
is not called, the mutex will be... | #include <mutex>
void manipulate_shared_data(std::mutex &pm) {
pm.lock();
// Perform work on shared data.
pm.unlock();
}
## Noncompliant Code Example
This noncompliant code example manipulates shared data and protects the critical section by locking the mutex. When it is finished, it unlocks the mutex.
Howeve... | #include <mutex>
void manipulate_shared_data(std::mutex &pm) {
pm.lock();
try {
// Perform work on shared data.
} catch (...) {
pm.unlock();
throw;
}
pm.unlock(); // in case no exceptions occur
}
#include <mutex>
void manipulate_shared_data(std::mutex &pm) {
std::lock_guard<std::mutex> lk(pm)... | ## Risk Assessment
If an exception occurs while a mutex is locked, deadlock may result.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CON51-CPP
Low
Probable
Yes
Yes
P6
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 10. Concurrency (CON) |
cplusplus | 88,046,449 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046449 | 2 | 10 | CON52-CPP | Prevent data races when accessing bit-fields from multiple threads | When accessing a bit-field, a thread may inadvertently access a separate bit-field in adjacent memory. This is because compilers are required to store multiple adjacent bit-fields in one storage unit whenever they fit. Consequently, data races may exist not just on a bit-field accessed by multiple threads but also on o... | struct MultiThreadedFlags {
unsigned int flag1 : 2;
unsigned int flag2 : 2;
};
MultiThreadedFlags flags;
void thread1() {
flags.flag1 = 1;
}
void thread2() {
flags.flag2 = 2;
}
Thread 1: register 0 = flags
Thread 1: register 0 &= ~mask(flag1)
Thread 2: register 0 = flags
Thread 2: register 0 &= ~mask(flag2)... | #include <mutex>
struct MultiThreadedFlags {
unsigned int flag1 : 2;
unsigned int flag2 : 2;
};
struct MtfMutex {
MultiThreadedFlags s;
std::mutex mutex;
};
MtfMutex flags;
void thread1() {
std::lock_guard<std::mutex> lk(flags.mutex);
flags.s.flag1 = 1;
}
void thread2() {
std::lock_guard<std::mutex... | ## Risk Assessment
Although the race window is narrow, an assignment or an expression can evaluate improperly because of misinterpreted data resulting in a corrupted running state or unintended information disclosure.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CON52-CPP
Medium
Probable
No
No
P4
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 10. Concurrency (CON) |
cplusplus | 88,046,455 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046455 | 2 | 10 | CON53-CPP | Avoid deadlock by locking in a predefined order | Mutexes are used to prevent multiple threads from causing a
data race
by accessing the same shared resource at the same time. Sometimes, when locking mutexes, multiple threads hold each other's lock, and the program consequently
deadlocks
. Four conditions are required for deadlock to occur:
mutual exclusion (At least ... | #include <mutex>
#include <thread>
class BankAccount {
int balance;
public:
std::mutex balanceMutex;
BankAccount() = delete;
explicit BankAccount(int initialAmount) : balance(initialAmount) {}
int get_balance() const { return balance; }
void set_balance(int amount) { balance = amount; }
};
int deposit(B... | #include <atomic>
#include <mutex>
#include <thread>
class BankAccount {
static std::atomic<unsigned int> globalId;
const unsigned int id;
int balance;
public:
std::mutex balanceMutex;
BankAccount() = delete;
explicit BankAccount(int initialAmount) : id(globalId++), balance(initialAmount) {}
unsigned in... | ## Risk Assessment
Deadlock prevents multiple threads from progressing, halting program execution. A
denial-of-service attack
is possible if the attacker can create the conditions for deadlock.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CON53-CPP
Low
Probable
No
No
P2
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 10. Concurrency (CON) |
cplusplus | 88,046,450 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046450 | 2 | 10 | CON54-CPP | Wrap functions that can spuriously wake up in a loop | The
wait()
,
wait_for()
, and
wait_until()
member functions of the
std::condition_variable
class temporarily cede possession of a mutex so that other threads that may be requesting the mutex can proceed. These functions must always be called from code that is protected by locking a mutex. The waiting thread resumes exe... | #include <condition_variable>
#include <mutex>
struct Node {
void *node;
struct Node *next;
};
static Node list;
static std::mutex m;
static std::condition_variable condition;
void consume_list_element(std::condition_variable &condition) {
std::unique_lock<std::mutex> lk(m);
if (list.next == nullptr)... | #include <condition_variable>
#include <mutex>
struct Node {
void *node;
struct Node *next;
};
static Node list;
static std::mutex m;
static std::condition_variable condition;
void consume_list_element() {
std::unique_lock<std::mutex> lk(m);
while (list.next == nullptr) {
condition.wait(lk);
}
... | null | SEI CERT C++ Coding Standard > 2 Rules > Rule 10. Concurrency (CON) |
cplusplus | 88,046,445 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046445 | 2 | 10 | CON55-CPP | Preserve thread safety and liveness when using condition variables | Both thread safety and
liveness
are concerns when using condition variables. The
thread-safety
property requires that all objects maintain consistent states in a multithreaded environment [
Lea 2000
]. The
liveness
property requires that every operation or function invocation execute to completion without interruption;... | #include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
std::mutex mutex;
std::condition_variable cond;
void run_step(size_t myStep) {
static size_t currentStep = 0;
std::unique_lock<std::mutex> lk(mutex);
std::cout << "Thread " << myStep << " has the lock" << std::endl;
while ... | #include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
std::mutex mutex;
std::condition_variable cond;
void run_step(size_t myStep) {
static size_t currentStep = 0;
std::unique_lock<std::mutex> lk(mutex);
std::cout << "Thread " << myStep << " has the lock" << std::endl;
while (... | ## Risk Assessment
Failing to preserve the thread safety and liveness of a program when using condition variables can lead to indefinite blocking and
denial of service
(DoS).
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CON55-CPP
Low
Unlikely
No
Yes
P2
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 10. Concurrency (CON) |
cplusplus | 88,046,858 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046858 | 2 | 10 | CON56-CPP | Do not speculatively lock a non-recursive mutex that is already owned by the calling thread | The C++ Standard Library supplies both recursive and non-recursive mutex classes used to protect
critical sections
. The recursive mutex classes (
std::recursive_mutex
and
std::recursive_timed_mutex
) differ from the non-recursive mutex classes (
std::mutex
,
std::timed_mutex
, and
std::shared_timed_mutex
) in that a r... | #include <mutex>
#include <thread>
std::mutex m;
void do_thread_safe_work();
void do_work() {
while (!m.try_lock()) {
// The lock is not owned yet, do other work while waiting.
do_thread_safe_work();
}
try {
// The mutex is now locked; perform work on shared resources.
// ...
// Release the... | #include <mutex>
#include <thread>
std::mutex m;
void do_thread_safe_work();
void do_work() {
while (!m.try_lock()) {
// The lock is not owned yet, do other work while waiting.
do_thread_safe_work();
}
try {
// The mutex is now locked; perform work on shared resources.
// ...
// Release the ... | ## Risk Assessment
Speculatively locking a non-recursive mutex in a recursive manner is undefined behavior that can lead to deadlock.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CON56-CPP
Low
Unlikely
No
No
P1
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 10. Concurrency (CON) |
cplusplus | 88,046,704 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046704 | 2 | 4 | CTR50-CPP | Guarantee that container indices and iterators are within the valid range | true
Better normative wording is badly needed.
Ensuring that array references are within the bounds of the array is almost entirely the responsibility of the programmer. Likewise, when using standard template library vectors, the programmer is responsible for ensuring integer indexes are within the bounds of the vector... | #include <cstddef>
void insert_in_table(int *table, std::size_t tableSize, int pos, int value) {
if (pos >= tableSize) {
// Handle error
return;
}
table[pos] = value;
}
#include <vector>
void insert_in_table(std::vector<int> &table, long long pos, int value) {
if (pos >= table.size()) {
// Hand... | #include <cstddef>
void insert_in_table(int *table, std::size_t tableSize, std::size_t pos, int value) {
if (pos >= tableSize) {
// Handle error
return;
}
table[pos] = value;
}
#include <cstddef>
#include <new>
void insert_in_table(int *table, std::size_t tableSize, std::size_t pos, int value) { // #1... | ## Risk Assessment
Using an invalid array or container index can result in an arbitrary memory overwrite or
abnormal program termination
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CTR50-CPP
High
Likely
No
No
P9
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 04. Containers (CTR) |
cplusplus | 88,046,457 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046457 | 2 | 4 | CTR51-CPP | Use valid references, pointers, and iterators to reference elements of a container | Iterators are a generalization of pointers that allow a C++ program to work with different data structures (containers) in a uniform manner [
ISO/IEC 14882-2014
]. Pointers, references, and iterators share a close relationship in which it is required that referencing values be done through a valid iterator, pointer, or... | #include <deque>
void f(const double *items, std::size_t count) {
std::deque<double> d;
auto pos = d.begin();
for (std::size_t i = 0; i < count; ++i, ++pos) {
d.insert(pos, items[i] + 41.0);
}
}
## Noncompliant Code Example
In this noncompliant code example,
pos
is invalidated after the first call to
ins... | #include <deque>
void f(const double *items, std::size_t count) {
std::deque<double> d;
auto pos = d.begin();
for (std::size_t i = 0; i < count; ++i, ++pos) {
pos = d.insert(pos, items[i] + 41.0);
}
}
#include <algorithm>
#include <deque>
#include <iterator>
void f(const double *items, std::size_t coun... | ## Risk Assessment
Using invalid references, pointers, or iterators to reference elements of a container results in undefined behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CTR51-CPP
High
Probable
No
No
P6
L2
Automated Detection
Tool
Version
Checker
Description
overflow_upon_dereference
ALLOC.U... | SEI CERT C++ Coding Standard > 2 Rules > Rule 04. Containers (CTR) |
cplusplus | 88,046,690 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046690 | 2 | 4 | CTR52-CPP | Guarantee that library functions do not overflow | Copying data into a container that is not large enough to hold that data results in a buffer overflow. To prevent such errors, data copied to the destination container must be restricted on the basis of the destination container's size, or preferably, the destination container must be guaranteed to be large enough to h... | #include <algorithm>
#include <vector>
void f(const std::vector<int> &src) {
std::vector<int> dest;
std::copy(src.begin(), src.end(), dest.begin());
// ...
}
#include <algorithm>
#include <vector>
void f() {
std::vector<int> v;
std::fill_n(v.begin(), 10, 0x42);
}
## Noncompliant Code Example
STL container... | #include <algorithm>
#include <vector>
void f(const std::vector<int> &src) {
// Initialize dest with src.size() default-inserted elements
std::vector<int> dest(src.size());
std::copy(src.begin(), src.end(), dest.begin());
// ...
}
#include <algorithm>
#include <iterator>
#include <vector>
void f(const std::ve... | ## Risk Assessment
Copying data to a buffer that is too small to hold the data results in a buffer overflow. Attackers can
exploit
this condition to execute arbitrary code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CTR52-CPP
High
Likely
No
No
P9
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 04. Containers (CTR) |
cplusplus | 88,046,456 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046456 | 2 | 4 | CTR53-CPP | Use valid iterator ranges | When iterating over elements of a container, the iterators used must iterate over a valid range. An iterator range is a pair of iterators that refer to the first and past-the-end elements of the range respectively.
A valid iterator range has all of the following characteristics:
Both iterators refer into the same conta... | #include <algorithm>
#include <iostream>
#include <vector>
void f(const std::vector<int> &c) {
std::for_each(c.end(), c.begin(), [](int i) { std::cout << i; });
}
#include <algorithm>
#include <iostream>
#include <vector>
void f(const std::vector<int> &c) {
std::vector<int>::const_iterator e;
std::for_each(c... | #include <algorithm>
#include <iostream>
#include <vector>
void f(const std::vector<int> &c) {
std::for_each(c.begin(), c.end(), [](int i) { std::cout << i; });
}
#include <algorithm>
#include <iostream>
#include <vector>
void f(const std::vector<int> &c) {
std::for_each(c.begin(), c.end(), [](int i) { std::co... | ## Risk Assessment
Using an invalid iterator range is similar to allowing a buffer overflow, which can lead to an attacker running arbitrary code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CTR53-CPP
High
Probable
No
No
P6
L2
Automated Detection
Tool
Version
Checker
Description
overflow_upon_derefere... | SEI CERT C++ Coding Standard > 2 Rules > Rule 04. Containers (CTR) |
cplusplus | 88,046,693 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046693 | 2 | 4 | CTR54-CPP | Do not subtract iterators that do not refer to the same container | When two pointers are subtracted, both must point to elements of the same array object or to one past the last element of the array object; the result is the difference of the subscripts of the two array elements. Similarly, when two iterators are subtracted (including via
std::distance()
), both iterators must refer t... | #include <cstddef>
#include <iostream>
template <typename Ty>
bool in_range(const Ty *test, const Ty *r, size_t n) {
return 0 < (test - r) && (test - r) < (std::ptrdiff_t)n;
}
void f() {
double foo[10];
double *x = &foo[0];
double bar;
std::cout << std::boolalpha << in_range(&bar, x, 10);
}
#include <ios... | #include <iostream>
template <typename Ty>
bool in_range(const Ty *test, const Ty *r, size_t n) {
auto *cur = reinterpret_cast<const unsigned char *>(r);
auto *end = reinterpret_cast<const unsigned char *>(r + n);
auto *testPtr = reinterpret_cast<const unsigned char *>(test);
for (; cur != end; ++cur) {
... | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CTR54-CPP
Medium
Probable
No
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
invalid_pointer_subtraction
invalid_pointer_comparison
LANG.STRUCT.CUP
LANG.STRUCT.SUP
Comparison of Unrelated Pointers
Subtraction of Unrelated Poi... | SEI CERT C++ Coding Standard > 2 Rules > Rule 04. Containers (CTR) |
cplusplus | 88,046,720 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046720 | 2 | 4 | CTR55-CPP | Do not use an additive operator on an iterator if the result would overflow | Expressions that have an integral type can be added to or subtracted from a pointer, resulting in a value of the pointer type. If the resulting pointer is not a valid member of the container, or one past the last element of the container, the behavior of the additive operator is
undefined
. The C++ Standard, [expr.add]... | #include <iostream>
#include <vector>
void f(const std::vector<int> &c) {
for (auto i = c.begin(), e = i + 20; i != e; ++i) {
std::cout << *i << std::endl;
}
}
## Noncompliant Code Example (std::vector)
In this noncompliant code example, a random access iterator from a
std::vector
is used in an additive expr... | #include <algorithm>
#include <vector>
void f(const std::vector<int> &c) {
const std::vector<int>::size_type maxSize = 20;
for (auto i = c.begin(), e = i + std::min(maxSize, c.size()); i != e; ++i) {
// ...
}
}
## Compliant Solution (std::vector)
This compliant solution assumes that the programmer's intenti... | ## Risk Assessment
If adding or subtracting an integer to a pointer results in a reference to an element outside the array or one past the last element of the array object, the behavior is
undefined
but frequently leads to a buffer overflow or buffer underrun, which can often be
exploited
to run arbitrary code. Iterato... | SEI CERT C++ Coding Standard > 2 Rules > Rule 04. Containers (CTR) |
cplusplus | 88,046,755 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046755 | 2 | 4 | CTR56-CPP | Do not use pointer arithmetic on polymorphic objects | The definition of
pointer arithmetic
from the C++ Standard, [expr.add], paragraph 7 [
ISO/IEC 14882-2014
], states the following:
For addition or subtraction, if the expressions
P
or
Q
have type “pointer to
cv
T
”, where
T
is different from the cv-unqualified array element type, the behavior is undefined. [
Note:
In pa... | #include <iostream>
// ... definitions for S, T, globI, globD ...
void f(const S *someSes, std::size_t count) {
for (const S *end = someSes + count; someSes != end; ++someSes) {
std::cout << someSes->i << std::endl;
}
}
int main() {
T test[5];
f(test, 5);
}
#include <iostream>
// ... definitions for... | #include <iostream>
// ... definitions for S, T, globI, globD ...
void f(const S * const *someSes, std::size_t count) {
for (const S * const *end = someSes + count; someSes != end; ++someSes) {
std::cout << (*someSes)->i << std::endl;
}
}
int main() {
S *test[] = {new T, new T, new T, new T, new T};
f(t... | ## Risk Assessment
Using arrays polymorphically can result in memory corruption, which could lead to an attacker being able to execute arbitrary code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CTR56-CPP
High
Likely
No
No
P9
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 04. Containers (CTR) |
cplusplus | 88,046,458 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046458 | 2 | 4 | CTR57-CPP | Provide a valid ordering predicate | Associative containers place a strict weak ordering requirement on their key comparison predicates
[
ISO/IEC 14882-2014
]
. A strict weak ordering has the following properties:
for all
x
:
x < x == false
(irreflexivity)
for all
x
,
y
: if
x < y
then
!(y < x)
(asymmetry)
for all
x
,
y
,
z
: if
x < y && y < z
then
x < z
... | #include <functional>
#include <iostream>
#include <set>
void f() {
std::set<int, std::less_equal<int>> s{5, 10, 20};
for (auto r = s.equal_range(10); r.first != r.second; ++r.first) {
std::cout << *r.first << std::endl;
}
}
#include <iostream>
#include <set>
class S {
int i, j;
public:
S(int i, int... | #include <iostream>
#include <set>
void f() {
std::set<int> s{5, 10, 20};
for (auto r = s.equal_range(10); r.first != r.second; ++r.first) {
std::cout << *r.first << std::endl;
}
}
#include <iostream>
#include <set>
#include <tuple>
class S {
int i, j;
public:
S(int i, int j) : i(i), j(j) {}
... | ## Risk Assessment
Using an invalid ordering rule can lead to erratic behavior or infinite loops.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CTR57-CPP
Low
Probable
No
No
P2
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 04. Containers (CTR) |
cplusplus | 88,046,679 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046679 | 2 | 4 | CTR58-CPP | Predicate function objects should not be mutable | true
This has nothing to do with CTR as a group, and everything to do with the algorithmic requirements of the STL. However, I cannot think of a better place for this rule to live (aside from MSC, and I think CTR is an improvement). If we wind up with an STL category, this should probably go there.
The C++ standard lib... | #include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <vector>
class MutablePredicate : public std::unary_function<int, bool> {
size_t timesCalled;
public:
MutablePredicate() : timesCalled(0) {}
bool operator()(const int &) {
return ++timesCalled == 3;
}
};
templa... | #include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <vector>
class MutablePredicate : public std::unary_function<int, bool> {
size_t timesCalled;
public:
MutablePredicate() : timesCalled(0) {}
bool operator()(const int &) {
return ++timesCalled == 3;
}
};
templa... | ## Risk Assessment
Using a predicate function object that contains state can produce unexpected values.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CTR58-CPP
Low
Likely
Yes
No
P6
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 04. Containers (CTR) |
cplusplus | 88,046,566 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046566 | 2 | 1 | DCL50-CPP | Do not define a C-style variadic function | Functions can be defined to accept more formal arguments at the call site than are specified by the parameter declaration clause. Such functions are called
variadic
functions because they can accept a variable number of arguments from a caller. C++ provides two mechanisms by which a variadic function can be defined: fu... | #include <cstdarg>
int add(int first, int second, ...) {
int r = first + second;
va_list va;
va_start(va, second);
while (int v = va_arg(va, int)) {
r += v;
}
va_end(va);
return r;
}
## Noncompliant Code Example
This noncompliant code example uses a C-style variadic function to add a series of int... | #include <type_traits>
template <typename Arg, typename std::enable_if<std::is_integral<Arg>::value>::type * = nullptr>
int add(Arg f, Arg s) { return f + s; }
template <typename Arg, typename... Ts, typename std::enable_if<std::is_integral<Arg>::value>::type * = nullptr>
int add(Arg f, Ts... rest) {
return f + a... | ## Risk Assessment
Incorrectly using a variadic function can result in
abnormal program termination
, unintended information disclosure, or execution of arbitrary code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL50-CPP
High
Probable
Yes
No
P12
L1 | SEI CERT C++ Coding Standard > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
cplusplus | 88,046,915 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046915 | 2 | 1 | DCL51-CPP | Do not declare or define a reserved identifier | true
Special note: [global.names] moved partially to [lex.name] in C++17. So whenever this gets updated to C++17, this content needs to be updated as well.
The C++ Standard, [reserved.names]
[
ISO/IEC 14882-2014
]
, specifies the following rules regarding reserved names
:
A translation unit that includes a standard lib... | #ifndef _MY_HEADER_H_
#define _MY_HEADER_H_
// Contents of <my_header.h>
#endif // _MY_HEADER_H_
#include <cstddef>
unsigned int operator"" x(const char *, std::size_t);
#include <cstddef> // std::for size_t
static const std::size_t _max_limit = 1024;
std::size_t _limit = 100;
unsigned int get_value(unsigned in... | #ifndef MY_HEADER_H
#define MY_HEADER_H
// Contents of <my_header.h>
#endif // MY_HEADER_H
#include <cstddef>
unsigned int operator"" _x(const char *, std::size_t);
#include <cstddef> // for size_t
static const std::size_t max_limit = 1024;
std::size_t limit = 100;
unsigned int get_value(unsigned int count) {
... | ## Risk Assessment
Using reserved identifiers can lead to incorrect program operation.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL51-CPP
Low
Unlikely
Yes
No
P2
L3
Automated Detection
Tool
Version
Checker
Description
reserved-identifier
Partially checked
CertC++-DCL51
-Wreserved-id-macro
-Wuser-def... | SEI CERT C++ Coding Standard > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
cplusplus | 88,046,733 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046733 | 2 | 1 | DCL52-CPP | Never qualify a reference type with const or volatile | C++ does not allow you to change the value of a reference type, effectively treating all references as being
const
qualified. The C++ Standard, [dcl.ref], paragraph 1 [
ISO/IEC 14882-2014
], states the following:
Cv-qualified references are ill-formed except when the cv-qualifiers are introduced through the use of a
ty... | #include <iostream>
void f(char c) {
char &const p = c;
p = 'p';
std::cout << c << std::endl;
}
warning C4227: anachronism used : qualifiers on reference are ignored
p
error: 'const' qualifier may not be applied to a reference
#include <iostream>
void f(char c) {
const char &p = c;
p = 'p'; // Error: ... | #include <iostream>
void f(char c) {
char &p = c;
p = 'p';
std::cout << c << std::endl;
}
## Compliant Solution
## This compliant solution removes theconstqualifier.
#ccccff
cpp
#include <iostream>
void f(char c) {
char &p = c;
p = 'p';
std::cout << c << std::endl;
} | ## Risk Assessment
A
const
or
volatile
reference type may result in undefined behavior instead of a fatal diagnostic, causing unexpected values to be stored and leading to possible data integrity violations.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL52-CPP
Low
Unlikely
Yes
Yes
P3
L3
Automated Det... | SEI CERT C++ Coding Standard > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
cplusplus | 88,046,604 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046604 | 2 | 1 | DCL53-CPP | Do not write syntactically ambiguous declarations | It is possible to devise syntax that can ambiguously be interpreted as either an expression statement or a declaration. Syntax of this sort is called a
vexing parse
because the compiler must use disambiguation rules to determine the semantic results. The C++ Standard, [stmt.ambig], paragraph 1 [
ISO/IEC 14882-2014
], i... | #include <mutex>
static std::mutex m;
static int shared_resource;
void increment_by_42() {
std::unique_lock<std::mutex>(m);
shared_resource += 42;
}
#include <iostream>
struct Widget {
Widget() { std::cout << "Constructed" << std::endl; }
};
void f() {
Widget w();
}
#include <iostream>
struct Widget {
... | #include <mutex>
static std::mutex m;
static int shared_resource;
void increment_by_42() {
std::unique_lock<std::mutex> lock(m);
shared_resource += 42;
}
#include <iostream>
struct Widget {
Widget() { std::cout << "Constructed" << std::endl; }
};
void f() {
Widget w1; // Elide the parentheses
Widget w2... | ## Risk Assessment
Syntactically ambiguous declarations can lead to unexpected program execution. However, it is likely that rudimentary testing would uncover violations of this rule.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL53-CPP
Low
Unlikely
Yes
No
P2
L3
Automated Detection
Tool
Version
Check... | SEI CERT C++ Coding Standard > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
cplusplus | 88,046,889 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046889 | 2 | 1 | DCL54-CPP | Overload allocation and deallocation functions as a pair in the same scope | Allocation and deallocation functions can be overloaded at both global and class scopes.
If an allocation function is overloaded in a given scope, the corresponding deallocation function must also be overloaded in the same scope (and vice versa).
Failure to overload the corresponding dynamic storage function is likely ... | #include <Windows.h>
#include <new>
void *operator new(std::size_t size) noexcept(false) {
static HANDLE h = ::HeapCreate(0, 0, 0); // Private, expandable heap.
if (h) {
return ::HeapAlloc(h, 0, size);
}
throw std::bad_alloc();
}
// No corresponding global delete operator defined.
#include <new>
exte... | #include <Windows.h>
#include <new>
class HeapAllocator {
static HANDLE h;
static bool init;
public:
static void *alloc(std::size_t size) noexcept(false) {
if (!init) {
h = ::HeapCreate(0, 0, 0); // Private, expandable heap.
init = true;
}
if (h) {
return ::HeapAlloc(h, 0, size)... | ## Risk Assessment
Mismatched usage of
new
and
delete
could lead to a
denial-of-service attack
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL54-CPP
Low
Probable
Yes
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
new-delete-pairwise
Partially checked
Axivion Bauhaus Suite
CertC++-DCL5... | SEI CERT C++ Coding Standard > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
cplusplus | 88,046,453 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046453 | 2 | 1 | DCL55-CPP | Avoid information leakage when passing a class object across a trust boundary | The C++ Standard, [class.mem], paragraph 13 [
ISO/IEC 14882-2014
], describes the layout of non-static data members of a non-union class, specifying the following:
Nonstatic data members of a (non-union) class with the same access control are allocated so that later members have higher addresses within a class object. ... | #include <cstddef>
struct test {
int a;
char b;
int c;
};
// Safely copy bytes to user space
extern int copy_to_user(void *dest, void *src, std::size_t size);
void do_stuff(void *usr_buf) {
test arg{1, 2, 3};
copy_to_user(usr_buf, &arg, sizeof(arg));
}
#include <cstddef>
struct test {
int a;
char... | #include <cstddef>
#include <cstring>
struct test {
int a;
char b;
int c;
};
// Safely copy bytes to user space.
extern int copy_to_user(void *dest, void *src, std::size_t size);
void do_stuff(void *usr_buf) {
test arg{1, 2, 3};
// May be larger than strictly needed.
unsigned char buf[sizeof(arg)];
... | ## Risk Assessment
Padding bits might inadvertently contain sensitive data such as pointers to kernel data structures or passwords. A pointer to such a structure could be passed to other functions, causing information leakage.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL55-CPP
Low
Unlikely
No
Yes
P... | SEI CERT C++ Coding Standard > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
cplusplus | 88,046,820 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046820 | 2 | 1 | DCL56-CPP | Avoid cycles during initialization of static objects | The C++ Standard, [stmt.dcl], paragraph 4
[
ISO/IEC 14882-2014
]
, states the following:
The zero-initialization (8.5) of all block-scope variables with static storage duration (3.7.1) or thread storage duration (3.7.2) is performed before any other initialization takes place. Constant initialization (3.6.2) of a block... | #include <stdexcept>
int fact(int i) noexcept(false) {
if (i < 0) {
// Negative factorials are undefined.
throw std::domain_error("i must be >= 0");
}
static const int cache[] = {
fact(0), fact(1), fact(2), fact(3), fact(4), fact(5),
fact(6), fact(7), fact(8), fact(9), fact(10), fact(11),
... | #include <stdexcept>
int fact(int i) noexcept(false) {
if (i < 0) {
// Negative factorials are undefined.
throw std::domain_error("i must be >= 0");
}
// Use the lazy-initialized cache.
static int cache[17];
if (i < (sizeof(cache) / sizeof(int))) {
if (0 == cache[i]) {
cache[i] = i > 0 ?... | ## Risk Assessment
Recursively reentering a function during the initialization of one of its static objects can result in an attacker being able to cause a crash or
denial of service
. Indeterminately ordered dynamic initialization can lead to undefined behavior due to accessing an uninitialized object.
Rule
Severity
L... | SEI CERT C++ Coding Standard > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
cplusplus | 88,046,363 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046363 | 2 | 1 | DCL57-CPP | Do not let exceptions escape from destructors or deallocation functions | Under certain circumstances, terminating a destructor,
operator delete
, or
operator delete[]
by throwing an exception can trigger
undefined behavior
.
For instance, the C++ Standard, [basic.stc.dynamic.deallocation], paragraph 3 [
ISO/IEC 14882-2014
], in part, states the following:
If a deallocation function terminat... | #include <stdexcept>
class S {
bool has_error() const;
public:
~S() noexcept(false) {
// Normal processing
if (has_error()) {
throw std::logic_error("Something bad");
}
}
};
#include <exception>
#include <stdexcept>
class S {
bool has_error() const;
public:
~S() noexcept(false) {
... | class SomeClass {
Bad bad_member;
public:
~SomeClass()
try {
// ...
} catch(...) {
// Catch exceptions thrown from noncompliant destructors of
// member objects or base class subobjects.
// NOTE: Flowing off the end of a destructor function-try-block causes
// the caught exception to be imp... | ## Risk Assessment
Attempting to throw exceptions from destructors or deallocation functions can result in undefined behavior, leading to resource leaks or
denial-of-service attacks
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL57-CPP
Low
Likely
Yes
Yes
P9
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
cplusplus | 88,046,686 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046686 | 2 | 1 | DCL58-CPP | Do not modify the standard namespaces | Namespaces introduce new declarative regions for declarations, reducing the likelihood of conflicting identifiers with other declarative regions. One feature of namespaces is that they can be further extended, even within separate translation units. For instance, the following declarations are well-formed.
namespace My... | namespace std {
int x;
}
#include <functional>
#include <iostream>
#include <string>
class MyString {
std::string data;
public:
MyString(const std::string &data) : data(data) {}
const std::string &get_data() const { return data; }
};
namespace std {
template <>
struct plus<string> : binary_function<strin... | namespace nonstd {
int x;
}
#include <functional>
#include <iostream>
#include <string>
class MyString {
std::string data;
public:
MyString(const std::string &data) : data(data) {}
const std::string &get_data() const { return data; }
};
struct my_plus : std::binary_function<std::string, MyString, std::st... | ## Risk Assessment
Altering the standard namespace can cause
undefined behavior
in the C++ standard library.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL58-CPP
High
Unlikely
Yes
No
P6
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
Dataset Card for SEI CERT C++ Coding Standard (Wiki rules)
Structured export of the SEI CERT C++ Coding Standard from the SEI wiki.
Dataset Details
Dataset Description
Tabular snapshot of CERT C++ secure coding rules with narrative text and illustrative compliant / noncompliant code where published on the wiki.
- Curated by: Derived from public SEI CERT wiki pages; packaged as CSV by the dataset maintainer.
- Funded by [optional]: [More Information Needed]
- Shared by [optional]: [More Information Needed]
- Language(s) (NLP): English (rule text and embedded code).
- License: Compilation distributed as
other; confirm terms with CMU SEI for redistribution.
Dataset Sources [optional]
- Repository: https://wiki.sei.cmu.edu/confluence/display/seccode/SEI+CERT+Coding+Standards
- Paper [optional]: SEI CERT C++ Coding Standard
- Demo [optional]: [More Information Needed]
Uses
Direct Use
C++ security linting research, courseware, and retrieval-augmented assistants.
Out-of-Scope Use
Not authoritative for compliance audits without verifying against the current standard.
Dataset Structure
All rows share the same columns (scraped from the SEI CERT Confluence wiki):
| Column | Description |
|---|---|
language |
Language identifier for the rule set |
page_id |
Confluence page id |
page_url |
Canonical wiki URL for the rule page |
chapter |
Chapter label when present |
section |
Section label when present |
rule_id |
Rule identifier (e.g. API00-C, CON50-J) |
title |
Short rule title |
intro |
Normative / explanatory text |
noncompliant_code |
Noncompliant example(s) when present |
compliant_solution |
Compliant example(s) when present |
risk_assessment |
Risk / severity notes when present |
breadcrumb |
Wiki breadcrumb trail when present |
Dataset Creation
Curation Rationale
Expose CERT C++ guidance in a uniform schema for tooling and ML workflows.
Source Data
Data Collection and Processing
Wiki scrape normalized to the shared CSV schema used across SEI CERT language exports.
Who are the source data producers?
[More Information Needed]
Annotations [optional]
Annotation process
[More Information Needed]
Who are the annotators?
[More Information Needed]
Personal and Sensitive Information
[More Information Needed]
Bias, Risks, and Limitations
[More Information Needed]
Recommendations
Users should be made aware of the risks, biases and limitations of the dataset. More information needed for further recommendations.
Citation [optional]
BibTeX:
[More Information Needed]
APA:
[More Information Needed]
Glossary [optional]
[More Information Needed]
More Information [optional]
[More Information Needed]
Dataset Card Authors [optional]
[More Information Needed]
Dataset Card Contact
[More Information Needed]
- Downloads last month
- 27