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) |
cplusplus | 88,046,421 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046421 | 2 | 1 | DCL59-CPP | Do not define an unnamed namespace in a header file | Unnamed namespaces are used to define a namespace that is unique to the translation unit, where the names contained within have internal linkage by default. The C++ Standard, [namespace.unnamed], paragraph 1 [
ISO/IEC 14882-2014
], states the following:
An
unnamed-namespace-definition
behaves as if it were replaced by:... | // a.h
#ifndef A_HEADER_FILE
#define A_HEADER_FILE
namespace {
int v;
}
#endif // A_HEADER_FILE
// a.cpp
#include "a.h"
#include <iostream>
void f() {
std::cout << "f(): " << v << std::endl;
v = 42;
// ...
}
// b.cpp
#include "a.h"
#include <iostream>
void g() {
std::cout << "g(): " << v << std::end... | // a.h
#ifndef A_HEADER_FILE
#define A_HEADER_FILE
extern int v;
#endif // A_HEADER_FILE
// a.cpp
#include "a.h"
#include <iostream>
int v; // Definition of global variable v
void f() {
std::cout << "f(): " << v << std::endl;
v = 42;
// ...
}
// b.cpp
#include "a.h"
#include <iostream>
void g() {
s... | ## Risk Assessment
Defining an unnamed namespace within a header file can cause data integrity violations and performance problems but is unlikely to go unnoticed with sufficient testing. One-definition rule violations result in
undefined behavior
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL59-CP... | SEI CERT C++ Coding Standard > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
cplusplus | 88,046,369 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046369 | 2 | 1 | DCL60-CPP | Obey the one-definition rule | Nontrivial C++ programs are generally divided into multiple translation units that are later linked together to form an executable. To support such a model, C++ restricts named object definitions to ensure that linking will behave deterministically by requiring a single definition for an object across all translation u... | // a.cpp
struct S {
int a;
};
// b.cpp
class S {
public:
int a;
};
// s.h
struct S {
char c;
int a;
};
void init_s(S &s);
// s.cpp
#include "s.h"
void init_s(S &s) {
s.c = 'a';
s.a = 12;
}
// a.cpp
#pragma pack(push, 1)
#include "s.h"
#pragma pack(pop)
void f() {
S s;
init_s(s);
}
const in... | // S.h
struct S {
int a;
};
// a.cpp
#include "S.h"
// b.cpp
#include "S.h"
// a.cpp
namespace {
struct S {
int a;
};
}
// b.cpp
namespace {
class S {
public:
int a;
};
}
// s.h
struct S {
char c;
int a;
};
void init_s(S &s);
// s.cpp
#include "s.h"
void init_s(S &s) {
s.c = 'a';
s.a = 12;
}... | ## Risk Assessment
Violating the ODR causes
undefined behavior
, which can result in exploits as well as
denial-of-service attacks
. As shown in "Support for Whole-Program Analysis and the Verification of the One-Definition Rule in C++" [
Quinlan 06
], failing to enforce the ODR enables a virtual function pointer attac... | SEI CERT C++ Coding Standard > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
cplusplus | 88,046,588 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046588 | 2 | 8 | ERR50-CPP | Do not abruptly terminate the program | The
std::abort()
,
std::quick_exit()
, and
std::_Exit()
functions are used to terminate the program in an immediate fashion. They do so without calling exit handlers registered with
std::atexit()
and without executing destructors for objects with automatic, thread, or static storage duration. How a system manages open ... | #include <cstdlib>
void throwing_func() noexcept(false);
void f() { // Not invoked by the program except as an exit handler.
throwing_func();
}
int main() {
if (0 != std::atexit(f)) {
// Handle error
}
// ...
}
## Noncompliant Code Example
In this noncompliant code example, the call to
f()
, which wa... | #include <cstdlib>
void throwing_func() noexcept(false);
void f() { // Not invoked by the program except as an exit handler.
try {
throwing_func();
} catch (...) {
// Handle error
}
}
int main() {
if (0 != std::atexit(f)) {
// Handle error
}
// ...
}
## Compliant Solution
## In this complian... | ## Risk Assessment
Allowing the application to
abnormally terminate
can lead to resources not being freed, closed, and so on. It is frequently a vector for
denial-of-service attacks
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR50-CPP
Low
Probable
No
No
P2
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 08. Exceptions and Error Handling (ERR) |
cplusplus | 88,046,367 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046367 | 2 | 8 | ERR51-CPP | Handle all exceptions | When an exception is thrown, control is transferred to the nearest handler with a type that matches the type of the exception thrown. If no matching handler is directly found within the handlers for a try block in which the exception is thrown, the search for a matching handler continues to dynamically search for handl... | void throwing_func() noexcept(false);
void f() {
throwing_func();
}
int main() {
f();
}
#include <thread>
void throwing_func() noexcept(false);
void thread_start() {
throwing_func();
}
void f() {
std::thread t(thread_start);
t.join();
}
## Noncompliant Code Example
In this noncompliant code example... | void throwing_func() noexcept(false);
void f() {
throwing_func();
}
int main() {
try {
f();
} catch (...) {
// Handle error
}
}
#include <thread>
void throwing_func() noexcept(false);
void thread_start(void) {
try {
throwing_func();
} catch (...) {
// Handle error
}
}
void f() {
... | ## Risk Assessment
Allowing the application to
abnormally terminate
can lead to resources not being freed, closed, and so on. It is frequently a vector for
denial-of-service attacks
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR51-CPP
Low
Probable
Yes
Yes
P6
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 08. Exceptions and Error Handling (ERR) |
cplusplus | 88,046,492 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046492 | 2 | 8 | ERR52-CPP | Do not use setjmp() or longjmp() | The C standard library facilities
setjmp()
and
longjmp()
can be used to simulate throwing and catching exceptions. However, these facilities bypass automatic resource management and can result in
undefined behavior
, commonly including resource leaks and
denial-of-service attacks
.
The C++ Standard, [support.runtime], ... | #include <csetjmp>
#include <iostream>
static jmp_buf env;
struct Counter {
static int instances;
Counter() { ++instances; }
~Counter() { --instances; }
};
int Counter::instances = 0;
void f() {
Counter c;
std::cout << "f(): Instances: " << Counter::instances << std::endl;
std::longjmp(env, 1);
}
int m... | #include <iostream>
struct Counter {
static int instances;
Counter() { ++instances; }
~Counter() { --instances; }
};
int Counter::instances = 0;
void f() {
Counter c;
std::cout << "f(): Instances: " << Counter::instances << std::endl;
throw "Exception";
}
int main() {
std::cout << "Before throw: Insta... | ## Risk Assessment
Using
setjmp()
and
longjmp()
could lead to a
denial-of-service attack
due to resources not being properly destroyed.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR52-CPP
Low
Probable
Yes
No
P4
L3
Automated Detection
Tool
Version
Checker
Description
include-setjmp
Fully checked
Cert... | SEI CERT C++ Coding Standard > 2 Rules > Rule 08. Exceptions and Error Handling (ERR) |
cplusplus | 88,046,587 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046587 | 2 | 8 | ERR53-CPP | Do not reference base classes or class data members in a constructor or destructor function-try-block handler | When an exception is caught by a
function-try-block
handler in a constructor, any fully constructed base classes and class members of the object are destroyed prior to entering the handler [
ISO/IEC 14882-2014
]. Similarly, when an exception is caught by a
function-try-block
handler in a destructor, all base classes an... | #include <string>
class C {
std::string str;
public:
C(const std::string &s) try : str(s) {
// ...
} catch (...) {
if (!str.empty()) {
// ...
}
}
};
## Noncompliant Code Example
In this noncompliant code example, the constructor for class
C
handles exceptions with a
function-try-block
. H... | #include <string>
class C {
std::string str;
public:
C(const std::string &s) try : str(s) {
// ...
} catch (...) {
if (!s.empty()) {
// ...
}
}
};
## Compliant Solution
In this compliant solution, the handler inspects the constructor parameter rather than the class data member, thereby avoi... | ## Risk Assessment
Accessing nonstatic data in a constructor's exception handler or a destructor's exception handler leads to
undefined behavior
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR53-CPP
Low
Unlikely
Yes
Yes
P3
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 08. Exceptions and Error Handling (ERR) |
cplusplus | 88,046,646 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046646 | 2 | 8 | ERR54-CPP | Catch handlers should order their parameter types from most derived to least derived | The C++ Standard, [except.handle], paragraph 4 [
ISO/IEC 14882-2014
], states the following:
The handlers for a try block are tried in order of appearance. That makes it possible to write handlers that can never be executed, for example by placing a handler for a derived class after a handler for a corresponding base c... | // Classes used for exception handling
class B {};
class D : public B {};
void f() {
try {
// ...
} catch (B &b) {
// ...
} catch (D &d) {
// ...
}
}
## Noncompliant Code Example
In this noncompliant code example, the first handler catches all exceptions of class
B
, as well as exceptions of class... | // Classes used for exception handling
class B {};
class D : public B {};
void f() {
try {
// ...
} catch (D &d) {
// ...
} catch (B &b) {
// ...
}
}
## Compliant Solution
In this compliant solution, the first handler catches all exceptions of class
D
, and the second handler catches all the other... | ## Risk Assessment
Exception handlers with inverted priorities cause unexpected control flow when an exception of the derived type occurs.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR54-CPP
Medium
Likely
Yes
Yes
P18
L1 | SEI CERT C++ Coding Standard > 2 Rules > Rule 08. Exceptions and Error Handling (ERR) |
cplusplus | 88,046,887 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046887 | 2 | 8 | ERR55-CPP | Honor exception specifications | The C++ Standard, [except.spec], paragraph 8
[
ISO/IEC 14882-2014
], states the following
:
A function is said to
allow
an exception of type
E
if the
constant-expression
in its
noexcept-specification
evaluates to
false
or its
dynamic-exception-specification
contains a type
T
for which a handler of type
T
would be a mat... | #include <cstddef>
#include <vector>
void f(std::vector<int> &v, size_t s) noexcept(true) {
v.resize(s); // May throw
}
#include <exception>
class Exception1 : public std::exception {};
class Exception2 : public std::exception {};
void foo() {
throw Exception2{}; // Okay because foo() promises nothing about ... | #include <cstddef>
#include <vector>
void f(std::vector<int> &v, size_t s) {
v.resize(s); // May throw, but that is okay
}
#include <exception>
class Exception1 : public std::exception {};
class Exception2 : public std::exception {};
void foo() {
throw Exception2{}; // Okay because foo() promises nothing about... | ## Risk Assessment
Throwing unexpected exceptions disrupts control flow and can cause premature termination and
denial of service
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR55-CPP
Low
Likely
No
Yes
P6
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 08. Exceptions and Error Handling (ERR) |
cplusplus | 88,046,334 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046334 | 2 | 8 | ERR56-CPP | Guarantee exception safety | Proper handling of errors and exceptional situations is essential for the continued correct operation of software. The preferred mechanism for reporting errors in a C++ program is exceptions rather than error codes. A number of core language facilities, including
dynamic_cast
,
operator new()
, and
typeid
, report fail... | #include <cstring>
class IntArray {
int *array;
std::size_t nElems;
public:
// ...
~IntArray() {
delete[] array;
}
IntArray(const IntArray& that); // nontrivial copy constructor
IntArray& operator=(const IntArray &rhs) {
if (this != &rhs) {
delete[] array;
array = nullptr;
... | #include <cstring>
class IntArray {
int *array;
std::size_t nElems;
public:
// ...
~IntArray() {
delete[] array;
}
IntArray(const IntArray& that); // nontrivial copy constructor
IntArray& operator=(const IntArray &rhs) {
int *tmp = nullptr;
if (rhs.nElems) {
tmp = new int[rhs.nElems... | ## Risk Assessment
Code that is not exception safe typically leads to resource leaks, causes the program to be left in an inconsistent or unexpected state, and ultimately results in undefined behavior at some point after the first exception is thrown.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR56-... | SEI CERT C++ Coding Standard > 2 Rules > Rule 08. Exceptions and Error Handling (ERR) |
cplusplus | 88,046,459 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046459 | 2 | 8 | ERR57-CPP | Do not leak resources when handling exceptions | Reclaiming resources when exceptions are thrown is important. An exception being thrown may result in cleanup code being bypassed or an object being left in a partially initialized state. Such a partially initialized object would violate basic exception safety, as described in
. It is preferable that resources be recla... | #include <new>
struct SomeType {
SomeType() noexcept; // Performs nontrivial initialization.
~SomeType(); // Performs nontrivial finalization.
void process_item() noexcept(false);
};
void f() {
SomeType *pst = new (std::nothrow) SomeType();
if (!pst) {
// Handle error
return;
}
try {
pst... | #include <new>
struct SomeType {
SomeType() noexcept; // Performs nontrivial initialization.
~SomeType(); // Performs nontrivial finalization.
void process_item() noexcept(false);
};
void f() {
SomeType *pst = new (std::nothrow) SomeType();
if (!pst) {
// Handle error
return;
}
try {
pst->p... | ## Risk Assessment
Memory and other resource leaks will eventually cause a program to crash. If an attacker can provoke repeated resource leaks by forcing an exception to be thrown through the submission of suitably crafted data, then the attacker can mount a
denial-of-service attack
.
Rule
Severity
Likelihood
Detectab... | SEI CERT C++ Coding Standard > 2 Rules > Rule 08. Exceptions and Error Handling (ERR) |
cplusplus | 88,046,575 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046575 | 2 | 8 | ERR58-CPP | Handle all exceptions thrown before main() begins executing | Not all exceptions can be caught, even with careful use of
function-try-blocks
. The C++ Standard, [except.handle], paragraph 13 [
ISO/IEC 14882-2014
], states the following:
Exceptions thrown in destructors of objects with static storage duration or in constructors of namespace scope objects with static storage durati... | struct S {
S() noexcept(false);
};
static S globalS;
#include <string>
static const std::string global("...");
int main()
try {
// ...
} catch(...) {
// IMPORTANT: Will not catch exceptions thrown
// from the constructor of global
}
extern int f() noexcept(false);
int i = f();
int main() {
// ...
}
... | struct S {
S() noexcept(false);
};
S &globalS() {
try {
static S s;
return s;
} catch (...) {
// Handle error, perhaps by logging it and gracefully terminating the application.
}
// Unreachable.
}
static const char *global = "...";
int main() {
// ...
}
#include <exception>
#include <string... | ## Risk Assessment
Throwing an exception that cannot be caught results in
abnormal program termination
and can lead to
denial-of-service attacks
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR58-CPP
Low
Likely
No
Yes
P6
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 08. Exceptions and Error Handling (ERR) |
cplusplus | 88,046,406 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046406 | 2 | 8 | ERR59-CPP | Do not throw an exception across execution boundaries | Throwing an exception requires collaboration between the execution of the
throw
expression and the passing of control to the appropriate
catch
statement, if one applies. This collaboration takes the form of runtime logic used to calculate the correct handler for the exception and is an implementation detail specific to... | // library.h
void func() noexcept(false); // Implemented by the library
// library.cpp
void func() noexcept(false) {
// ...
if (/* ... */) {
throw 42;
}
}
// application.cpp
#include "library.h"
void f() {
try {
func();
} catch(int &e) {
// Handle error
}
}
## Noncompliant Code Example
In ... | // library.h
int func() noexcept(true); // Implemented by the library
// library.cpp
int func() noexcept(true) {
// ...
if (/* ... */) {
return 42;
}
// ...
return 0;
}
// application.cpp
#include "library.h"
void f() {
if (int err = func()) {
// Handle error
}
}
## Compliant Solution
In this... | ## Risk Assessment
The effects of throwing an exception across execution boundaries depends on the
implementation details
of the exception-handling mechanics. They can range from correct or benign behavior to
undefined behavior
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR59-CPP
High
Probable
No
N... | SEI CERT C++ Coding Standard > 2 Rules > Rule 08. Exceptions and Error Handling (ERR) |
cplusplus | 88,046,483 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046483 | 2 | 8 | ERR60-CPP | Exception objects must be nothrow copy constructible | When an exception is thrown, the exception object operand of the
throw
expression is copied into a temporary object that is used to initialize the handler. The C++ Standard, [except.throw], paragraph 3 [
ISO/IEC 14882-2014
], in part, states the following:
Throwing an exception copy-initializes a temporary object, call... | #include <exception>
#include <string>
class S : public std::exception {
std::string m;
public:
S(const char *msg) : m(msg) {}
const char *what() const noexcept override {
return m.c_str();
}
};
void g() {
// If some condition doesn't hold...
throw S("Condition did not hold");
}
void f() {
t... | #include <stdexcept>
#include <type_traits>
struct S : std::runtime_error {
S(const char *msg) : std::runtime_error(msg) {}
};
static_assert(std::is_nothrow_copy_constructible<S>::value,
"S must be nothrow copy constructible");
void g() {
// If some condition doesn't hold...
throw S("Condition d... | ## Risk Assessment
Allowing the application to
abnormally terminate
can lead to resources not being freed, closed, and so on. It is frequently a vector for
denial-of-service attacks
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR60-CPP
Low
Probable
Yes
No
P4
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 08. Exceptions and Error Handling (ERR) |
cplusplus | 88,046,409 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046409 | 2 | 8 | ERR61-CPP | Catch exceptions by lvalue reference | When an exception is thrown, the value of the object in the throw expression is used to initialize an anonymous temporary object called the
exception object
. The type of this exception object is used to transfer control to the nearest catch handler, which contains an exception declaration with a matching type. The C++... | #include <exception>
#include <iostream>
struct S : std::exception {
const char *what() const noexcept override {
return "My custom exception";
}
};
void f() {
try {
throw S();
} catch (std::exception e) {
std::cout << e.what() << std::endl;
}
}
## Noncompliant Code Example
In this noncomplia... | #include <exception>
#include <iostream>
struct S : std::exception {
const char *what() const noexcept override {
return "My custom exception";
}
};
void f() {
try {
throw S();
} catch (std::exception &e) {
std::cout << e.what() << std::endl;
}
}
## Compliant Solution
In this compliant soluti... | ## Risk Assessment
Object slicing can result in abnormal program execution. This generally is not a problem for exceptions, but it can lead to unexpected behavior depending on the assumptions made by the exception handler.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR61-CPP
Low
Unlikely
Yes
No
P2
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 08. Exceptions and Error Handling (ERR) |
cplusplus | 88,046,440 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046440 | 2 | 8 | ERR62-CPP | Detect errors when converting a string to a number | The process of parsing an integer or floating-point number from a string can produce many errors. The string might not contain a number. It might contain a number of the correct type that is out of range (such as an integer that is larger than
INT_MAX
). The string may also contain extra information after the number, w... | #include <iostream>
void f() {
int i, j;
std::cin >> i >> j;
// ...
}
## Noncompliant Code Example
In this noncompliant code example, multiple numeric values are converted from the standard input stream. However, if the text received from the standard input stream cannot be converted into a numeric value that c... | #include <iostream>
void f() {
int i, j;
std::cin.exceptions(std::istream::failbit | std::istream::badbit);
try {
std::cin >> i >> j;
// ...
} catch (std::istream::failure &E) {
// Handle error
}
}
#include <iostream>
#include <limits>
void f() {
int i;
std::cin >> i;
if (std::cin.f... | ## Risk Assessment
It is rare for a violation of this rule to result in a security
vulnerability
unless it occurs in security-sensitive code. However, violations of this rule can easily result in lost or misinterpreted data.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
ERR62-CPP
Medium
Unlikely
Yes
No
... | SEI CERT C++ Coding Standard > 2 Rules > Rule 08. Exceptions and Error Handling (ERR) |
cplusplus | 88,046,625 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046625 | 2 | 2 | EXP50-CPP | Do not depend on the order of evaluation for side effects | In C++, modifying an object, calling a library I/O function, accessing a
volatile
-qualified value, or calling a function that performs one of these actions are ways to modify the state of the execution environment. These actions are called
side effects
. All relationships between value computations and side effects ca... | void f(int i, const int *b) {
int a = i + b[++i];
// ...
}
extern void func(int i, int j);
void f(int i) {
func(i++, i);
}
#include <iostream>
void f(int i) {
std::cout << i++ << i << std::endl;
}
extern void c(int i, int j);
int glob;
int a() {
return glob + 10;
}
int b() {
glob = 42;
return gl... | void f(int i, const int *b) {
++i;
int a = i + b[i];
// ...
}
void f(int i, const int *b) {
int a = i + b[i + 1];
++i;
// ...
}
extern void func(int i, int j);
void f(int i) {
i++;
func(i, i);
}
extern void func(int i, int j);
void f(int i) {
int j = i++;
func(j, i);
}
#include <iostream>
... | ## Risk Assessment
Attempting to modify an object in an unsequenced or indeterminately sequenced evaluation may cause that object to take on an unexpected value, which can lead to
unexpected program behavior
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP50-CPP
Medium
Probable
No
Yes
P8
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,319 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046319 | 2 | 2 | EXP51-CPP | Do not delete an array through a pointer of the incorrect type | The C++ Standard, [expr.delete], paragraph 3 [
ISO/IEC 14882-2014
], states the following:
In the first alternative (
delete object
), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static t... | struct Base {
virtual ~Base() = default;
};
struct Derived final : Base {};
void f() {
Base *b = new Derived[10];
// ...
delete [] b;
}
## Noncompliant Code Example
In this noncompliant code example, an array of
Derived
objects is created and the pointer is stored in a
Base *
. Despite
Base::~Base
() bein... | struct Base {
virtual ~Base() = default;
};
struct Derived final : Base {};
void f() {
Derived *b = new Derived[10];
// ...
delete [] b;
}
## Compliant Solution
In this compliant solution, the static type of
b
is
Derived *
, which removes the
undefined behavior
when indexing into the array as well as when... | ## Risk Assessment
Attempting to destroy an array of polymorphic objects through the incorrect static type is undefined behavior. In practice, potential consequences include abnormal program execution and memory leaks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP51-CPP
Low
Unlikely
No
No
P1
L3
Auto... | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,497 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046497 | 2 | 2 | EXP52-CPP | Do not rely on side effects in unevaluated operands | Some expressions involve operands that are
unevaluated
. The C++ Standard, [expr], paragraph 8
[
ISO/IEC 14882-2014
] states the following
:
In some contexts,
unevaluated operands
appear. An unevaluated operand is not evaluated. An unevaluated operand is considered a full-expression. [Note: In an unevaluated operand, a... | #include <iostream>
void f() {
int a = 14;
int b = sizeof(a++);
std::cout << a << ", " << b << std::endl;
}
#include <iostream>
void f() {
int i = 0;
decltype(i++) h = 12;
std::cout << i;
}
## Noncompliant Code Example (sizeof)
## In this noncompliant code example, the expressiona++is not evaluated.
#FFC... | #include <iostream>
void f() {
int a = 14;
int b = sizeof(a);
++a;
std::cout << a << ", " << b << std::endl;
}
#include <iostream>
void f() {
int i = 0;
decltype(i) h = 12;
++i;
std::cout << i;
}
## Compliant Solution (sizeof)
## In this compliant solution, the variableais incremented outside of thes... | ## Risk Assessment
If expressions that appear to produce side effects are an unevaluated operand, the results may be different than expected. Depending on how this result is used, it can lead to unintended program behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP52-CPP
Low
Unlikely
Yes
Yes
P3
... | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,609 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046609 | 2 | 2 | EXP53-CPP | Do not read uninitialized memory | Local, automatic variables assume unexpected values if they are read before they are initialized. The C++ Standard, [dcl.init], paragraph 12 [
ISO/IEC 14882-2014
], states the following:
If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic... | #include <iostream>
void f() {
int i;
std::cout << i;
}
#include <iostream>
void f() {
int *i = new int;
std::cout << i << ", " << *i;
}
class S {
int c;
public:
int f(int i) const { return i + c; }
};
void f() {
S s;
int i = s.f(10);
}
#include <new>
void f() {
int *p;
try {
p = ne... | #include <iostream>
void f() {
int i = 0;
std::cout << i;
}
#include <iostream>
void f() {
int *i = new int(12);
std::cout << i << ", " << *i;
}
int *i = new int(); // zero-initializes *i
int *j = new int{}; // zero-initializes *j
int *k = new int(12); // initializes *k to 12
int *l = new int{12}; // init... | ## Risk Assessment
Reading uninitialized variables is undefined behavior and can result in unexpected program behavior. In some cases, these
security flaws
may allow the execution of arbitrary code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP53-CPP
High
Probable
No
Yes
P12
L1 | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,649 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046649 | 2 | 2 | EXP54-CPP | Do not access an object outside of its lifetime | Every object has a lifetime in which it can be used in a well-defined manner. The lifetime of an object begins when sufficient, properly aligned storage has been obtained for it and its initialization is complete. The lifetime of an object ends when a nontrivial destructor, if any, is called for the object and the stor... | struct S {
void mem_fn();
};
void f() {
S *s;
s->mem_fn();
}
struct B {};
struct D1 : virtual B {};
struct D2 : virtual B {};
struct S : D1, D2 {};
void f(const B *b) {}
void g() {
S *s = new S;
// Use s
delete s;
f(s);
}
int *g() {
int i = 12;
return &i;
}
void h(int *i);
void f() {... | struct S {
void mem_fn();
};
void f() {
S *s = new S;
s->mem_fn();
delete s;
}
struct B {};
struct D1 : virtual B {};
struct D2 : virtual B {};
struct S : D1, D2 {};
void f(const B *b) {}
void g() {
S *s = new S;
// Use s
f(s);
delete s;
}
int *g() {
static int i = 12;
return &i;
}
v... | ## Risk Assessment
Referencing an object outside of its lifetime can result in an attacker being able to run arbitrary code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP54-CPP
High
Probable
No
No
P6
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,592 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046592 | 2 | 2 | EXP55-CPP | Do not access a cv-qualified object through a cv-unqualified type | The C++ Standard, [dcl.type.cv], paragraph 4 [
ISO/IEC 14882-2014
], states the following:
Except that any class member declared
mutable
can be modified, any attempt to modify a
const
object during its lifetime results in undefined behavior.
Similarly, paragraph 6 states the following:
What constitutes an access to an ... | void g(const int &ci) {
int &ir = const_cast<int &>(ci);
ir = 42;
}
void f() {
const int i = 4;
g(i);
}
#include <iostream>
class S {
int cachedValue;
int compute_value() const; // expensive
public:
S() : cachedValue(0) {}
// ...
int get_value() const {
if (!cachedValue) {
const... | void g(int &i) {
i = 42;
}
void f() {
int i = 4;
g(i);
}
#include <iostream>
class S {
mutable int cachedValue;
int compute_value() const; // expensive
public:
S() : cachedValue(0) {}
// ...
int get_value() const {
if (!cachedValue) {
cachedValue = compute_value();
} ... | ## Risk Assessment
If the object is declared as being constant, it may reside in write-protected memory at runtime. Attempting to modify such an object may lead to
abnormal program termination
or a
denial-of-service attack
. If an object is declared as being volatile, the compiler can make no assumptions regarding acce... | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,880 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046880 | 2 | 2 | EXP56-CPP | Do not call a function with a mismatched language linkage | C++ allows a degree of interoperability with other languages through the use of language linkage specifications. These specifications affect the way in which functions are called or data is accessed. By default, all function types, as well as function and variable names, with external linkage have C++ language linkage,... | extern "java" typedef void (*java_callback)(int);
extern void call_java_fn_ptr(java_callback callback);
void callback_func(int);
void f() {
call_java_fn_ptr(callback_func);
}
## Noncompliant Code Example
In this noncompliant code example, the
call_java_fn_ptr()
function expects to receive a function pointer with... | extern "java" typedef void (*java_callback)(int);
extern void call_java_fn_ptr(java_callback callback);
extern "java" void callback_func(int);
void f() {
call_java_fn_ptr(callback_func);
}
## Compliant Solution
In this compliant solution, the
callback_func()
function is given
"java"
language linkage to match the l... | ## Risk Assessment
Mismatched language linkage specifications generally do not create exploitable security vulnerabilities between the C and C++ language linkages. However, other language linkages exist where the undefined behavior is more likely to result in abnormal program execution, including exploitable vulnerabil... | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,579 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046579 | 2 | 2 | EXP57-CPP | Do not cast or delete pointers to incomplete classes | Referring to objects of incomplete class type, also known as
forward declarations
, is a common practice. One such common usage is with the "pimpl idiom" [
Sutter 00
] whereby an opaque pointer is used to hide implementation details from a public-facing API. However, attempting to delete a pointer to an object of incom... | class Handle {
class Body *impl; // Declaration of a pointer to an incomplete class
public:
~Handle() { delete impl; } // Deletion of pointer to an incomplete class
// ...
};
// File1.h
class B {
protected:
double d;
public:
B() : d(1.0) {}
};
// File2.h
void g(class D *);
class B *get_d(); // Returns a p... | class Handle {
class Body *impl; // Declaration of a pointer to an incomplete class
public:
~Handle();
// ...
};
// Elsewhere
class Body { /* ... */ };
Handle::~Handle() {
delete impl;
}
#include <memory>
class Handle {
std::shared_ptr<class Body> impl;
public:
Handle();
~Handle() {}
// .... | ## Risk Assessment
Casting pointers or references to incomplete classes can result in bad addresses. Deleting a pointer to an incomplete class results in undefined behavior if the class has a nontrivial destructor. Doing so can cause program termination, a runtime signal, or resource leaks.
Rule
Severity
Likelihood
Det... | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,431 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046431 | 2 | 2 | EXP58-CPP | Pass an object of the correct type to va_start | While rule
forbids creation of such functions, they may still be defined when that function has external, C language linkage. Under these circumstances, care must be taken when invoking the
va_start()
macro. The C-standard library macro
va_start()
imposes several semantic restrictions on the type of the value of its se... | #include <cstdarg>
extern "C" void f(float a, ...) {
va_list list;
va_start(list, a);
// ...
va_end(list);
}
#include <cstdarg>
#include <iostream>
extern "C" void f(int &a, ...) {
va_list list;
va_start(list, a);
if (a) {
std::cout << a << ", " << va_arg(list, int);
a = 100; // Assign someth... | #include <cstdarg>
extern "C" void f(double a, ...) {
va_list list;
va_start(list, a);
// ...
va_end(list);
}
#include <cstdarg>
#include <iostream>
extern "C" void f(int *a, ...) {
va_list list;
va_start(list, a);
if (a && *a) {
std::cout << a << ", " << va_arg(list, int);
*a = 100; // Assig... | ## Risk Assessment
Passing an object of an unsupported type as the second argument to
va_start()
can result in
undefined behavior
that might be
exploited
to cause data integrity violations.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP58-CPP
Medium
Unlikely
Yes
No
P4
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,343 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046343 | 2 | 2 | EXP59-CPP | Use offsetof() on valid types and members | The
offsetof()
macro is defined by the C Standard as a portable way to determine the offset, expressed in bytes, from the start of the object to a given member of that object. The C Standard, subclause 7.17, paragraph 3 [
ISO/IEC 9899:1999
], in part, specifies the following:
offsetof(type, member-designator)
which exp... | #include <cstddef>
struct D {
virtual void f() {}
int i;
};
void f() {
size_t off = offsetof(D, i);
// ...
}
#include <cstddef>
struct S {
static int i;
// ...
};
int S::i = 0;
extern void store_in_some_buffer(void *buffer, size_t offset, int val);
extern void *buffer;
void f() {
size_t off = o... | #include <cstddef>
struct D {
virtual void f() {}
struct InnerStandardLayout {
int i;
} inner;
};
void f() {
size_t off = offsetof(D::InnerStandardLayout, i);
// ...
}
#include <cstddef>
struct S {
static int i;
// ...
};
int S::i = 0;
extern void store_in_some_buffer(void *buffer, size_t offse... | ## Risk Assessment
Passing an invalid type or member to
offsetof()
can result in
undefined behavior
that might be
exploited
to cause data integrity violations or result in incorrect values from the macro expansion.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP59-CPP
Medium
Unlikely
Yes
No
P4
L3
Auto... | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,486 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046486 | 2 | 2 | EXP60-CPP | Do not pass a nonstandard-layout type object across execution boundaries | Standard-layout types can be used to communicate with code written in other programming languages, as the layout of the type is strictly specified. The C++ Standard, [class], paragraph 7 [
ISO/IEC 14882-2014
], defines a standard-layout class as a class that
does not have virtual functions,
has the same access control ... | // library.h
struct S {
virtual void f() { /* ... */ }
};
void func(S &s); // Implemented by the library, calls S::f()
// application.cpp
#include "library.h"
void g() {
S s;
func(s);
}
struct B {
int i, j;
};
struct D : B {
float f;
};
extern "Fortran" void func(void *);
void foo(D *d) {
func(... | // library.h
#include <type_traits>
struct S {
void f() { /* ... */ } // No longer virtual
};
static_assert(std::is_standard_layout<S>::value, "S is required to be a standard layout type");
void func(S &s); // Implemented by the library, calls S::f()
// application.cpp
#include "library.h"
void g() {
S s;
fun... | ## Risk Assessment
The effects of passing objects of nonstandard-layout type across execution boundaries depends on what operations are performed on the object within the callee as well as what subsequent operations are performed on the object from the caller. The effects can range from correct or benign behavior to
un... | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,422 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046422 | 2 | 2 | EXP61-CPP | A lambda object must not outlive any of its reference captured objects | Lambda expressions may capture objects with automatic storage duration from the set of enclosing scopes (called the
reaching scope
) for use in the lambda's function body. These captures may be either explicit, by specifying the object to capture in the lambda's
capture-list
, or implicit, by using a
capture-default
an... | auto g() {
int i = 12;
return [&] {
i = 100;
return i;
};
}
void f() {
int j = g()();
}
auto g(int val) {
auto outer = [val] {
int i = val;
auto inner = [&] {
i += 30;
return i;
};
return inner;
};
return outer();
}
void f() {
auto fn = g(12);
int j = fn();
}
##... | auto g() {
int i = 12;
return [=] () mutable {
i = 100;
return i;
};
}
void f() {
int j = g()();
}
auto g(int val) {
auto outer = [val] {
int i = val;
auto inner = [i] {
return i + 30;
};
return inner;
};
return outer();
}
void f() {
auto fn = g(12);
int j = fn();
}
#... | ## Risk Assessment
Referencing an object outside of its lifetime can result in an attacker being able to run arbitrary code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP61-CPP
High
Probable
No
No
P6
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,482 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046482 | 2 | 2 | EXP62-CPP | Do not access the bits of an object representation that are not part of the object's value representation | The C++ Standard, [basic.types], paragraph 9 [
ISO/IEC 14882-2014
], states the following:
The
object representation
of an object of type
T
is the sequence of
N
unsigned char
objects taken up by the object of type
T
, where
N
equals
sizeof(T)
. The
value representation
of an object is the set of bits that hold the valu... | #include <cstring>
struct S {
unsigned char buffType;
int size;
};
void f(const S &s1, const S &s2) {
if (!std::memcmp(&s1, &s2, sizeof(S))) {
// ...
}
}
#include <cstring>
struct S {
int i, j, k;
// ...
virtual void f();
};
void f() {
S *s = new S;
// ...
std::memset(s, 0, sizeof(S));... | struct S {
unsigned char buffType;
int size;
friend bool operator==(const S &lhs, const S &rhs) {
return lhs.buffType == rhs.buffType &&
lhs.size == rhs.size;
}
};
void f(const S &s1, const S &s2) {
if (s1 == s2) {
// ...
}
}
struct S {
int i, j, k;
// ...
virtual void f()... | ## Risk Assessment
The effects of accessing bits of an object representation that are not part of the object's value representation can range from
implementation-defined behavior
(such as assuming the layout of fields with differing access controls) to code execution
vulnerabilities
(such as overwriting the vtable poin... | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,395 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046395 | 2 | 2 | EXP63-CPP | Do not rely on the value of a moved-from object | Many types, including user-defined types and types provided by the Standard Template Library, support move semantics. Except in rare circumstances, an object of a type that supports move operations (move initialization or move assignment) will be left in a valid, but unspecified state after the object's value has been ... | #include <iostream>
#include <string>
void g(std::string v) {
std::cout << v << std::endl;
}
void f() {
std::string s;
for (unsigned i = 0; i < 10; ++i) {
s.append(1, static_cast<char>('0' + i));
g(std::move(s));
}
}
0
01
012
0123
01234
012345
0123456
01234567
012345678
0123456789
#include <algorith... | #include <iostream>
#include <string>
void g(std::string v) {
std::cout << v << std::endl;
}
void f() {
for (unsigned i = 0; i < 10; ++i) {
std::string s(1, static_cast<char>('0' + i));
g(std::move(s));
}
}
#include <algorithm>
#include <iostream>
#include <vector>
void f(std::vector<int> &c) {
aut... | ## Risk Assessment
The state of a moved-from object is generally valid, but unspecified. Relying on unspecified values can lead to abnormal program termination as well as data integrity violations.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
EXP63-CPP
Medium
Probable
Yes
No
P8
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 02. Expressions (EXP) |
cplusplus | 88,046,808 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046808 | 2 | 7 | FIO50-CPP | Do not alternately input and output from a file stream without an intervening positioning call | The C++ Standard, [filebuf], paragraph 2 [
ISO/IEC 14882-2014
], states the following:
The restrictions on reading and writing a sequence controlled by an object of class
basic_filebuf<charT, traits>
are the same as for reading and writing with the Standard C library
FILE
s.
The C Standard, subclause 7.19.5.3, paragrap... | #include <fstream>
#include <string>
void f(const std::string &fileName) {
std::fstream file(fileName);
if (!file.is_open()) {
// Handle error
return;
}
file << "Output some data";
std::string str;
file >> str;
}
## Noncompliant Code Example
This noncompliant code example appends data to the en... | #include <fstream>
#include <string>
void f(const std::string &fileName) {
std::fstream file(fileName);
if (!file.is_open()) {
// Handle error
return;
}
file << "Output some data";
std::string str;
file.seekg(0, std::ios::beg);
file >> str;
}
## Compliant Solution
In this compliant solution... | ## Risk Assessment
Alternately inputting and outputting from a stream without an intervening flush or positioning call is
undefined behavior
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO50-CPP
Low
Likely
Yes
No
P6
L2
Automated Detection
Tool
Version
Checker
Description
Axivion Bauhaus Suite
CertC+... | SEI CERT C++ Coding Standard > 2 Rules > Rule 07. Input Output (FIO) |
cplusplus | 88,046,824 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046824 | 2 | 7 | FIO51-CPP | Close files when they are no longer needed | A call to the
std::basic_filebuf<T>::open()
function must be matched with a call to
std::basic_filebuf<T>::close()
before the lifetime of the last pointer that stores the return value of the call has ended or before normal program termination, whichever occurs first.
Note that
std::basic_ifstream<T>
,
std::basic_ofstre... | #include <exception>
#include <fstream>
#include <string>
void f(const std::string &fileName) {
std::fstream file(fileName);
if (!file.is_open()) {
// Handle error
return;
}
// ...
std::terminate();
}
## Noncompliant Code Example
In this noncompliant code example, a
std::fstream
object
file
is const... | #include <exception>
#include <fstream>
#include <string>
void f(const std::string &fileName) {
std::fstream file(fileName);
if (!file.is_open()) {
// Handle error
return;
}
// ...
file.close();
if (file.fail()) {
// Handle error
}
std::terminate();
}
#include <exception>
#include <fstream... | ## Risk Assessment
Failing to properly close files may allow an attacker to exhaust system resources and can increase the risk that data written into in-memory file buffers will not be flushed in the event of
abnormal program termination
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
FIO51-CPP
Medium
U... | SEI CERT C++ Coding Standard > 2 Rules > Rule 07. Input Output (FIO) |
cplusplus | 88,046,622 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046622 | 2 | 3 | INT50-CPP | Do not cast to an out-of-range enumeration value | Enumerations in C++ come in two forms:
scoped
enumerations in which the underlying type is fixed and
unscoped
enumerations in which the underlying type may or may not be fixed. The range of values that can be represented by either form of enumeration may include enumerator values not specified by the enumeration itself... | enum EnumType {
First,
Second,
Third
};
void f(int intVar) {
EnumType enumVar = static_cast<EnumType>(intVar);
if (enumVar < First || enumVar > Third) {
// Handle error
}
}
## Noncompliant Code Example (Bounds Checking)
This noncompliant code example attempts to check whether a given value is within ... | enum EnumType {
First,
Second,
Third
};
void f(int intVar) {
if (intVar < First || intVar > Third) {
// Handle error
}
EnumType enumVar = static_cast<EnumType>(intVar);
}
enum class EnumType {
First,
Second,
Third
};
void f(int intVar) {
EnumType enumVar = static_cast<EnumType>(intVar);
}
en... | ## Risk Assessment
It is possible for unspecified values to result in a buffer overflow, leading to the execution of arbitrary code by an attacker. However, because enumerators are rarely used for indexing into arrays or other forms of pointer arithmetic, it is more likely that this scenario will result in data integri... | SEI CERT C++ Coding Standard > 2 Rules > Rule 03. Integers (INT) |
cplusplus | 88,046,754 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046754 | 2 | 6 | MEM50-CPP | 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
. Pointers to memory that has been deallocated ar... | #include <new>
struct S {
void f();
};
void g() noexcept(false) {
S *s = new S;
// ...
delete s;
// ...
s->f();
}
#include <iostream>
#include <memory>
#include <cstring>
int main(int argc, const char *argv[]) {
const char *s = "";
if (argc > 1) {
enum { BufferSize = 32 };
try {
std... | #include <new>
struct S {
void f();
};
void g() noexcept(false) {
S *s = new S;
// ...
s->f();
delete s;
}
struct S {
void f();
};
void g() {
S s;
// ...
s.f();
}
#include <iostream>
#include <memory>
#include <cstring>
int main(int argc, const char *argv[]) {
std::unique_ptr<char[]> buff;
... | ## Risk Assessment
Reading previously dynamically allocated memory after it has been deallocated can lead to
abnormal program termination
and
denial-of-service attacks
. Writing memory that has been deallocated can lead to the execution of arbitrary code with the permissions of the vulnerable process.
Rule
Severity
Lik... | SEI CERT C++ Coding Standard > 2 Rules > Rule 06. Memory Management (MEM) |
cplusplus | 88,046,362 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046362 | 2 | 6 | MEM51-CPP | Properly deallocate dynamically allocated resources | The C programming language provides several ways to allocate memory, such as
std::malloc()
,
std::calloc()
, and
std::realloc()
, which can be used by a C++ program. However, the C programming language defines only a single way to free the allocated memory:
std::free()
. See
and
for rules specifically regarding C alloc... | #include <iostream>
struct S {
S() { std::cout << "S::S()" << std::endl; }
~S() { std::cout << "S::~S()" << std::endl; }
};
void f() {
alignas(struct S) char space[sizeof(struct S)];
S *s1 = new (&space) S;
// ...
delete s1;
}
struct P {};
class C {
P *p;
public:
C(P *p) : p(p) {}
~C() { del... | #include <iostream>
struct S {
S() { std::cout << "S::S()" << std::endl; }
~S() { std::cout << "S::~S()" << std::endl; }
};
void f() {
alignas(struct S) char space[sizeof(struct S)];
S *s1 = new (&space) S;
// ...
s1->~S();
}
struct P {};
class C {
P *p;
public:
C(P *p) : p(p) {}
C(const C... | ## Risk Assessment
Passing a pointer value to a deallocation function that was not previously obtained by the matching allocation function results in
undefined behavior
, which can lead to exploitable
vulnerabilities
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
MEM51-CPP
High
Likely
No
No
P9
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 06. Memory Management (MEM) |
cplusplus | 88,046,779 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046779 | 2 | 6 | MEM52-CPP | Detect and handle memory allocation errors | The default memory allocation operator,
::operator new(std::size_t)
, throws a
std::bad_alloc
exception if the allocation fails. Therefore, you need not check whether calling
::operator new(std::size_t)
results in
nullptr
. The nonthrowing form,
::operator new(std::size_t, const std::nothrow_t &)
, does not throw an ex... | #include <cstring>
void f(const int *array, std::size_t size) noexcept {
int *copy = new int[size];
std::memcpy(copy, array, size * sizeof(*copy));
// ...
delete [] copy;
}
struct A { /* ... */ };
struct B { /* ... */ };
void g(A *, B *);
void f() {
g(new A, new B);
}
## Noncompliant Code Example
In th... | #include <cstring>
#include <new>
void f(const int *array, std::size_t size) noexcept {
int *copy = new (std::nothrow) int[size];
if (!copy) {
// Handle error
return;
}
std::memcpy(copy, array, size * sizeof(*copy));
// ...
delete [] copy;
}
#include <cstring>
#include <new>
void f(const int *a... | ## Risk Assessment
Failing to detect allocation failures can lead to
abnormal program termination
and
denial-of-service attacks
.
If the vulnerable program references memory offset from the return value, an attacker can exploit the program to read or write arbitrary memory. This
vulnerability
has been used to execute a... | SEI CERT C++ Coding Standard > 2 Rules > Rule 06. Memory Management (MEM) |
cplusplus | 88,046,356 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046356 | 2 | 6 | MEM53-CPP | Explicitly construct and destruct objects when manually managing object lifetime | The creation of dynamically allocated objects in C++ happens in two stages. The first stage is responsible for allocating sufficient memory to store the object, and the second stage is responsible for initializing the newly allocated chunk of memory, depending on the type of the object being created.
Similarly, the des... | #include <cstdlib>
struct S {
S();
void f();
};
void g() {
S *s = static_cast<S *>(std::malloc(sizeof(S)));
s->f();
std::free(s);
}
#include <memory>
template <typename T, typename Alloc = std::allocator<T>>
class Container {
T *underlyingStorage;
size_t numElements;
void copy_elements(T *... | #include <cstdlib>
#include <new>
struct S {
S();
void f();
};
void g() {
void *ptr = std::malloc(sizeof(S));
S *s = new (ptr) S;
s->f();
s->~S();
std::free(ptr);
}
#include <memory>
template <typename T, typename Alloc = std::allocator<T>>
class Container {
T *underlyingStorage;
size_t numE... | ## Risk Assessment
Failing to properly construct or destroy an object leaves its internal state inconsistent, which can result in
undefined behavior
and accidental information exposure.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
MEM53-CPP
High
Likely
No
No
P9
L2
Automated Detection
Tool
Version
Check... | SEI CERT C++ Coding Standard > 2 Rules > Rule 06. Memory Management (MEM) |
cplusplus | 88,046,443 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046443 | 2 | 6 | MEM54-CPP | Provide placement new with properly aligned pointers to sufficient storage capacity | When invoked by a
new
expression for a given type, the default global non-placement forms of
operator new
attempt to allocate sufficient storage for an object of the type and, if successful, return a pointer with alignment suitable for any object with a fundamental alignment requirement. However, the default placement
... | #include <new>
void f() {
short s;
long *lp = ::new (&s) long;
}
#include <new>
void f() {
char c; // Used elsewhere in the function
unsigned char buffer[sizeof(long)];
long *lp = ::new (buffer) long;
// ...
}
#include <cstddef>
#include <new>
struct S {
S ();
~S ();
};
void f() {
const unsi... | #include <new>
void f() {
char c; // Used elsewhere in the function
alignas(long) unsigned char buffer[sizeof(long)];
long *lp = ::new (buffer) long;
// ...
}
#include <new>
void f() {
char c; // Used elsewhere in the function
std::aligned_storage<sizeof(long), alignof(long)>::type buffer;
long *lp... | ## Risk Assessment
Passing improperly aligned pointers or pointers to insufficient storage to placement
new
expressions can result in
undefined behavior
, including buffer overflow and
abnormal termination
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
MEM54-CPP
High
Likely
No
No
P9
L2
Automated Detect... | SEI CERT C++ Coding Standard > 2 Rules > Rule 06. Memory Management (MEM) |
cplusplus | 88,046,441 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046441 | 2 | 6 | MEM55-CPP | Honor replacement dynamic storage management requirements | Dynamic memory allocation and deallocation functions can be globally replaced by custom implementations, as specified by [replacement.functions], paragraph 2, of the C++ Standard [
ISO/IEC 14882-2014
]. For instance, a user may profile the dynamic memory usage of an application and decide that the default allocator is ... | #include <new>
void *operator new(std::size_t size) {
extern void *alloc_mem(std::size_t); // Implemented elsewhere; may return nullptr
return alloc_mem(size);
}
void operator delete(void *ptr) noexcept; // Defined elsewhere
void operator delete(void *ptr, std::size_t) noexcept; // Defined elsewhere
## Noncompl... | #include <new>
void *operator new(std::size_t size) {
extern void *alloc_mem(std::size_t); // Implemented elsewhere; may return nullptr
if (void *ret = alloc_mem(size)) {
return ret;
}
throw std::bad_alloc();
}
void operator delete(void *ptr) noexcept; // Defined elsewhere
void operator delete(void *ptr,... | ## Risk Assessment
Failing to meet the stated requirements for a replaceable dynamic storage function leads to
undefined behavior
. The severity of risk depends heavily on the caller of the allocation functions, but in some situations, dereferencing a null pointer can lead to the execution of arbitrary code [
Jack 2007... | SEI CERT C++ Coding Standard > 2 Rules > Rule 06. Memory Management (MEM) |
cplusplus | 88,046,438 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046438 | 2 | 6 | MEM56-CPP | Do not store an already-owned pointer value in an unrelated smart pointer | Smart pointers such as
std::unique_ptr
and
std::shared_ptr
encode pointer ownership semantics as part of the type system. They wrap a pointer value, provide pointer-like semantics through
operator *()
and
operator->()
member functions, and control the lifetime of the pointer they manage. When a smart pointer is constru... | #include <memory>
void f() {
int *i = new int;
std::shared_ptr<int> p1(i);
std::shared_ptr<int> p2(i);
}
#include <memory>
struct B {
virtual ~B() = default; // Polymorphic object
// ...
};
struct D : B {};
void g(std::shared_ptr<D> derived);
void f() {
std::shared_ptr<B> poly(new D);
// ...
g(std:... | #include <memory>
void f() {
std::shared_ptr<int> p1 = std::make_shared<int>();
std::shared_ptr<int> p2(p1);
}
#include <memory>
struct B {
virtual ~B() = default; // Polymorphic object
// ...
};
struct D : B {};
void g(std::shared_ptr<D> derived);
void f() {
std::shared_ptr<B> poly(new D);
// ...
g(... | ## Risk Assessment
Passing a pointer value to a deallocation function that was not previously obtained by the matching allocation function results in
undefined behavior
, which can lead to exploitable
vulnerabilities
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
MEM56-CPP
High
Likely
No
No
P9
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 06. Memory Management (MEM) |
cplusplus | 88,046,470 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046470 | 2 | 6 | MEM57-CPP | Avoid using default operator new for over-aligned types | The non-placement
new
expression is specified to invoke an allocation function to allocate storage for an object of the specified type. When successful, the allocation function, in turn, is required to return a pointer to storage with alignment suitable for any object with a fundamental alignment requirement. Although ... | struct alignas(32) Vector {
char elems[32];
};
Vector *f() {
Vector *pv = new Vector;
return pv;
}
## Noncompliant Code Example
In the following noncompliant code example, the new expression is used to invoke the default
operator new
to obtain storage in which to then construct an object of the user-defined typ... | #include <cstdlib>
#include <new>
struct alignas(32) Vector {
char elems[32];
static void *operator new(size_t nbytes) {
if (void *p = std::aligned_alloc(alignof(Vector), nbytes)) {
return p;
}
throw std::bad_alloc();
}
static void operator delete(void *p) {
free(p);
}
};
Vector *f() {... | ## Risk Assessment
Using improperly aligned pointers results in
undefined behavior
, typically leading to
abnormal termination
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
MEM57-CPP
Medium
Unlikely
No
No
P2
L3
Automated Detection
Tool
Version
Checker
Description
default-new-overaligned-type
Fully che... | SEI CERT C++ Coding Standard > 2 Rules > Rule 06. Memory Management (MEM) |
cplusplus | 88,046,554 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046554 | 2 | 49 | MSC50-CPP | Do not use std::rand() 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, exposed through the C++ standard library through
<cstdlib>
as
std::rand()
, makes no guarantees as to the quali... | #include <cstdlib>
#include <string>
void f() {
std::string id("ID"); // Holds the ID, starting with the characters "ID" followed
// by a random integer in the range [0-10000].
id += std::to_string(std::rand() % 10000);
// ...
}
## Noncompliant Code Example
The following noncompliant co... | #include <random>
#include <string>
void f() {
std::string id("ID"); // Holds the ID, starting with the characters "ID" followed
// by a random integer in the range [0-10000].
std::uniform_int_distribution<int> distribution(0, 10000);
std::random_device rd;
std::mt19937 engine(rd());
... | ## Risk Assessment
Using the
std::rand()
function could lead to predictable random numbers.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
MSC50-CPP
Medium
Unlikely
Yes
No
P4
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 49. Miscellaneous (MSC) |
cplusplus | 88,046,590 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046590 | 2 | 49 | MSC51-CPP | Ensure your random number generator is properly seeded | 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 <random>
#include <iostream>
void f() {
std::mt19937 engine;
for (int i = 0; i < 10; ++i) {
std::cout << engine() << ", ";
}
}
1st run: 3499211612, 581869302, 3890346734, 3586334585, 545404204, 4161255391, 3922919429, 949333985, 2715962298, 1323567403,
2nd run: 3499211612, 581869302, 3890346734... | #include <random>
#include <iostream>
void f() {
std::random_device dev;
std::mt19937 engine(dev());
for (int i = 0; i < 10; ++i) {
std::cout << engine() << ", ";
}
}
1st run: 3921124303, 1253168518, 1183339582, 197772533, 83186419, 2599073270, 3238222340, 101548389, 296330365, 3335314032,
2nd run: 2... | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
MSC51-CPP
Medium
Likely
Yes
Yes
P18
L1 | SEI CERT C++ Coding Standard > 2 Rules > Rule 49. Miscellaneous (MSC) |
cplusplus | 88,046,353 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046353 | 2 | 49 | MSC52-CPP | Value-returning functions must return a value from all exit paths | The C++ Standard, [stmt.return], paragraph 2 [
ISO/IEC 14882-2014
], states the following:
Flowing off the end of a function is equivalent to a
return
with no value; this results in undefined behavior in a value-returning function.
A value-returning function must return a value from all code paths; otherwise, it will r... | int absolute_value(int a) {
if (a < 0) {
return -a;
}
}
#include <vector>
std::size_t f(std::vector<int> &v, std::size_t s) try {
v.resize(s);
return s;
} catch (...) {
}
## Noncompliant Code Example
In this noncompliant code example, the programmer forgot to return the input value for positive input, s... | int absolute_value(int a) {
if (a < 0) {
return -a;
}
return a;
}
#include <vector>
std::size_t f(std::vector<int> &v, std::size_t s) try {
v.resize(s);
return s;
} catch (...) {
return 0;
}
## Compliant Solution
## In this compliant solution, all code paths now return a value.
#ccccff
cpp
int absol... | ## Risk Assessment
Failing to return a value from a code path in a value-returning function results in
undefined behavior
that might be
exploited
to cause data integrity violations.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
MSC52-CPP
Medium
Probable
Yes
No
P8
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 49. Miscellaneous (MSC) |
cplusplus | 88,046,346 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046346 | 2 | 49 | MSC53-CPP | Do not return from a function declared [[noreturn]] | The
[[noreturn]]
attribute specifies that a function does not return. The C++ Standard, [dcl.attr.noreturn] paragraph 2
[
ISO/IEC 14882-2014
], states the following:
If a function
f
is called where
f
was previously declared with the
noreturn
attribute and
f
eventually returns, the behavior is undefined.
A function that... | #include <cstdlib>
[[noreturn]] void f(int i) {
if (i > 0)
throw "Received positive input";
else if (i < 0)
std::exit(0);
}
## Noncompliant Code Example
In this noncompliant code example, if the value
0
is passed, control will flow off the end of the function, resulting in an implicit return and
undefine... | #include <cstdlib>
[[noreturn]] void f(int i) {
if (i > 0)
throw "Received positive input";
std::exit(0);
}
## Compliant Solution
## In this compliant solution, the function does not return on any code path.
#ccccff
cpp
#include <cstdlib>
[[noreturn]] void f(int i) {
if (i > 0)
throw "Received positive input... | ## Risk Assessment
Returning from a function marked
[[noreturn]]
results in
undefined behavior
that might be
exploited
to cause data-integrity violations.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
MSC53-CPP
Medium
Unlikely
Yes
No
P4
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 49. Miscellaneous (MSC) |
cplusplus | 88,046,360 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046360 | 2 | 49 | MSC54-CPP | A signal handler must be a plain old function | The C++14 Standard, [support.runtime], paragraph 10
[
ISO/IEC 14882-2014
]
, states the following:
The common subset of the C and C++ languages consists of all declarations, definitions, and expressions that may appear in a well-formed C++ program and also in a conforming C program. A POF (“plain old function”) is a fu... | #include <csignal>
static void sig_handler(int sig) {
// Implementation details elided.
}
void install_signal_handler() {
if (SIG_ERR == std::signal(SIGTERM, sig_handler)) {
// Handle error
}
}
#include <csignal>
static void g() noexcept(false);
extern "C" void sig_handler(int sig) {
try {
g();
... | #include <csignal>
extern "C" void sig_handler(int sig) {
// Implementation details elided.
}
void install_signal_handler() {
if (SIG_ERR == std::signal(SIGTERM, sig_handler)) {
// Handle error
}
}
#include <csignal>
volatile sig_atomic_t signal_flag = 0;
static void g() noexcept(false);
extern "C" void... | ## Risk Assessment
Failing to use a plain old function as a signal handler can result in
implementation-defined behavior
as well as
undefined behavior
. Given the number of features that exist in C++ that do not also exist in C, the consequences that arise from failure to comply with this rule can range from benign (ha... | SEI CERT C++ Coding Standard > 2 Rules > Rule 49. Miscellaneous (MSC) |
cplusplus | 88,046,570 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046570 | 2 | 9 | OOP50-CPP | Do not invoke virtual functions from constructors or destructors | Virtual functions allow for the choice of member function calls to be determined at run time based on the dynamic type of the object that the member function is being called on. This convention supports object-oriented programming practices commonly associated with object inheritance and function overriding. When calli... | struct B {
B() { seize(); }
virtual ~B() { release(); }
protected:
virtual void seize();
virtual void release();
};
struct D : B {
virtual ~D() = default;
protected:
void seize() override {
B::seize();
// Get derived resources...
}
void release() override {
// Release derived resource... | class B {
void seize_mine();
void release_mine();
public:
B() { seize_mine(); }
virtual ~B() { release_mine(); }
protected:
virtual void seize() { seize_mine(); }
virtual void release() { release_mine(); }
};
class D : public B {
void seize_mine();
void release_mine();
public:
D() { seize_mine... | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
OOP50-CPP
Low
Unlikely
Yes
No
P2
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 09. Object Oriented Programming (OOP) |
cplusplus | 88,046,913 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046913 | 2 | 9 | OOP51-CPP | Do not slice derived objects | An object deriving from a base class typically contains additional member variables that extend the base class. When by-value assigning or copying an object of the derived type to an object of the base type, those additional member variables are not copied because the base class contains insufficient space in which to ... | #include <iostream>
#include <string>
class Employee {
std::string name;
protected:
virtual void print(std::ostream &os) const {
os << "Employee: " << get_name() << std::endl;
}
public:
Employee(const std::string &name) : name(name) {}
const std::string &get_name() const { return name; }
fr... | // Remainder of code unchanged...
void f(const Employee *e) {
if (e) {
std::cout << *e;
}
}
int main() {
Employee coder("Joe Smith");
Employee typist("Bill Jones");
Manager designer("Jane Doe", typist);
f(&coder);
f(&typist);
f(&designer);
}
Employee: Joe Smith
Employee: Bill Jones
Manager: J... | ## Risk Assessment
Slicing results in information loss, which could lead to abnormal program execution or
denial-of-service attacks
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
OOP51-CPP
Low
Probable
No
No
P2
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 09. Object Oriented Programming (OOP) |
cplusplus | 88,046,565 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046565 | 2 | 9 | OOP52-CPP | Do not delete a polymorphic object without a virtual destructor | The C++ Standard, [expr.delete], paragraph 3
[
ISO/IEC 14882-2014
],
states the following:
In the first alternative (
delete object
), if the static type of the object to be deleted is different from its dynamic type, the static type shall be a base class of the dynamic type of the object to be deleted and the static t... | struct Base {
virtual void f();
};
struct Derived : Base {};
void f() {
Base *b = new Derived();
// ...
delete b;
}
#include <memory>
struct Base {
virtual void f();
};
struct Derived : Base {};
void f() {
std::unique_ptr<Base> b = std::make_unique<Derived>();
}
## Noncompliant Code Example
In t... | struct Base {
virtual ~Base() = default;
virtual void f();
};
struct Derived : Base {};
void f() {
Base *b = new Derived();
// ...
delete b;
}
## Compliant Solution
In this compliant solution, the destructor for
Base
has an explicitly declared
virtual
destructor, ensuring that the polymorphic delete operat... | ## Risk Assessment
Attempting to destruct a polymorphic object that does not have a
virtual
destructor declared results in
undefined behavior
. In practice, potential consequences include
abnormal program termination
and memory leaks.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
OOP52-CPP
Low
Likely
No... | SEI CERT C++ Coding Standard > 2 Rules > Rule 09. Object Oriented Programming (OOP) |
cplusplus | 88,046,709 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046709 | 2 | 9 | OOP53-CPP | Write constructor member initializers in the canonical order | The member initializer list for a class constructor allows members to be initialized to specified values and for base class constructors to be called with specific arguments. However, the order in which initialization occurs is fixed and does not depend on the order written in the member initializer list. The C++ Stand... | class C {
int dependsOnSomeVal;
int someVal;
public:
C(int val) : someVal(val), dependsOnSomeVal(someVal + 1) {}
};
class B1 {
int val;
public:
B1(int val) : val(val) {}
};
class B2 {
int otherVal;
public:
B2(int otherVal) : otherVal(otherVal) {}
int get_other_val() const { return otherVal; }
};... | class C {
int someVal;
int dependsOnSomeVal;
public:
C(int val) : someVal(val), dependsOnSomeVal(someVal + 1) {}
};
class B1 {
int val;
public:
B1(int val) : val(val) {}
};
class B2 {
int otherVal;
public:
B2(int otherVal) : otherVal(otherVal) {}
};
class D : B1, B2 {
public:
D(int a) : B1(a), ... | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
OOP53-CPP
Medium
Unlikely
Yes
Yes
P6
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 09. Object Oriented Programming (OOP) |
cplusplus | 88,046,496 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046496 | 2 | 9 | OOP54-CPP | Gracefully handle self-copy assignment | Self-copy assignment can occur in situations of varying complexity, but essentially, all self-copy assignments entail some variation of the following.
#include <utility>
struct S { /* ... */ }
void f() {
S s;
s = s; // Self-copy assignment
}
User-provided copy operators must properly handle self-copy assignment.
The po... | #include <new>
struct S { S(const S &) noexcept; /* ... */ };
class T {
int n;
S *s1;
public:
T(const T &rhs) : n(rhs.n), s1(rhs.s1 ? new S(*rhs.s1) : nullptr) {}
~T() { delete s1; }
// ...
T& operator=(const T &rhs) {
n = rhs.n;
delete s1;
s1 = new S(*rhs.s1);
return *this;
}
};... | #include <new>
struct S { S(const S &) noexcept; /* ... */ };
class T {
int n;
S *s1;
public:
T(const T &rhs) : n(rhs.n), s1(rhs.s1 ? new S(*rhs.s1) : nullptr) {}
~T() { delete s1; }
// ...
T& operator=(const T &rhs) {
if (this != &rhs) {
n = rhs.n;
delete s1;
try {
s1... | ## Risk Assessment
Allowing a copy assignment operator to corrupt an object could lead to
undefined behavior
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
OOP54-CPP
Low
Probable
Yes
No
P4
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 09. Object Oriented Programming (OOP) |
cplusplus | 88,046,847 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046847 | 2 | 9 | OOP55-CPP | Do not use pointer-to-member operators to access nonexistent members | The pointer-to-member operators
.*
and
->*
are used to obtain an object or a function as though it were a member of an underlying object. For instance, the following are functionally equivalent ways to call the member function
f()
on the object
o
.
struct S {
void f() {}
};
void func() {
S o;
void (S::*pm)() = &S::f;
o... | struct B {
virtual ~B() = default;
};
struct D : B {
virtual ~D() = default;
virtual void g() { /* ... */ }
};
void f() {
B *b = new B;
// ...
void (B::*gptr)() = static_cast<void(B::*)()>(&D::g);
(b->*gptr)();
delete b;
}
struct B {
virtual ~B() = default;
};
struct D : B {
virtual ~D() = d... | struct B {
virtual ~B() = default;
};
struct D : B {
virtual ~D() = default;
virtual void g() { /* ... */ }
};
void f() {
B *b = new D; // Corrected the dynamic object type.
// ...
void (D::*gptr)() = &D::g; // Moved static_cast to the next line.
(static_cast<D *>(b)->*gptr)();
delete b;
}
struct B... | ## Risk Assessment
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
OOP55-CPP
High
Probable
No
No
P6
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 09. Object Oriented Programming (OOP) |
cplusplus | 88,046,352 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046352 | 2 | 9 | OOP56-CPP | Honor replacement handler requirements | The
handler
functions
new_handler
,
terminate_handler
, and
unexpected_handler
can be globally replaced by custom
implementations
, as specified by [handler.functions], paragraph 2, of the C++ Standard [
ISO/IEC 14882-2014
]. For instance, an application could set a custom termination handler by calling
std::set_termin... | #include <new>
void custom_new_handler() {
// Returns number of bytes freed.
extern std::size_t reclaim_resources();
reclaim_resources();
}
int main() {
std::set_new_handler(custom_new_handler);
// ...
}
## Noncompliant Code Example
In this noncompliant code example, a replacement
new_handler
is writte... | #include <new>
void custom_new_handler() noexcept(false) {
// Returns number of bytes freed.
extern std::size_t reclaim_resources();
if (0 == reclaim_resources()) {
throw std::bad_alloc();
}
}
int main() {
std::set_new_handler(custom_new_handler);
// ...
}
## Compliant Solution
In this compliant s... | ## Risk Assessment
Failing to meet the required behavior for a replacement handler results in
undefined behavior
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
OOP56-CPP
Low
Probable
No
No
P2
L3 | SEI CERT C++ Coding Standard > 2 Rules > Rule 09. Object Oriented Programming (OOP) |
cplusplus | 88,046,484 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046484 | 2 | 9 | OOP57-CPP | Prefer special member functions and overloaded operators to C Standard Library functions | Several C standard library functions perform bytewise operations on objects. For instance,
std::memcmp()
compares the bytes comprising the object representation of two objects, and
std::memcpy()
copies the bytes comprising an object representation into a destination buffer. However, for some object types, it results in... | #include <cstring>
#include <iostream>
class C {
int scalingFactor;
int otherData;
public:
C() : scalingFactor(1) {}
void set_other_data(int i);
int f(int i) {
return i / scalingFactor;
}
// ...
};
void f() {
C c;
// ... Code that mutates c ...
// Reinitialize c to its default st... | #include <iostream>
#include <utility>
class C {
int scalingFactor;
int otherData;
public:
C() : scalingFactor(1) {}
void set_other_data(int i);
int f(int i) {
return i / scalingFactor;
}
// ...
};
template <typename T>
T& clear(T &o) {
using std::swap;
T empty;
swap(o, empty);
return... | ## Risk Assessment
Most violations of this rule will result in abnormal program behavior. However, overwriting
implementation
details of the object representation can lead to code execution
vulnerabilities
.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
OOP57-CPP
High
Probable
Yes
No
P12
L1
Automated De... | SEI CERT C++ Coding Standard > 2 Rules > Rule 09. Object Oriented Programming (OOP) |
cplusplus | 88,046,465 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046465 | 2 | 9 | OOP58-CPP | Copy operations must not mutate the source object | Copy operations (copy constructors and copy assignment operators) are expected to copy the salient properties of a source object into the destination object, with the resulting object being a "copy" of the original. What is considered to be a salient property of the type is type-dependent, but for types that expose com... | #include <algorithm>
#include <vector>
class A {
mutable int m;
public:
A() : m(0) {}
explicit A(int m) : m(m) {}
A(const A &other) : m(other.m) {
other.m = 0;
}
A& operator=(const A &other) {
if (&other != this) {
m = other.m;
other.m = 0;
}
return *this;
}
int ... | #include <algorithm>
#include <vector>
class A {
int m;
public:
A() : m(0) {}
explicit A(int m) : m(m) {}
A(const A &other) : m(other.m) {}
A(A &&other) : m(other.m) { other.m = 0; }
A& operator=(const A &other) {
if (&other != this) {
m = other.m;
}
return *this;
}
A& oper... | ## Risk Assessment
Copy operations that mutate the source operand or global state can lead to unexpected program behavior. Using such a type in a Standard Template Library container or algorithm can also lead to undefined behavior.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
OOP58-CPP
Low
Likely
Yes
N... | SEI CERT C++ Coding Standard > 2 Rules > Rule 09. Object Oriented Programming (OOP) |
cplusplus | 88,046,731 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046731 | 2 | 5 | STR50-CPP | 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 2013
]. To prevent such errors, either limit copies through truncation or, preferably, ensure that the destination is of sufficient size to hold the dat... | #include <iostream>
void f() {
char buf[12];
std::cin >> buf;
}
#include <iostream>
void f() {
char bufOne[12];
char bufTwo[12];
std::cin.width(12);
std::cin >> bufOne;
std::cin >> bufTwo;
}
#include <fstream>
#include <string>
void f(std::istream &in) {
char buffer[32];
try {
in.read(buff... | #include <iostream>
#include <string>
void f() {
std::string input;
std::string stringOne, stringTwo;
std::cin >> stringOne >> stringTwo;
}
#include <fstream>
#include <string>
void f(std::istream &in) {
char buffer[32];
try {
in.read(buffer, sizeof(buffer));
} catch (std::ios_base::failure &e) {
... | ## 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
STR50-CPP
High
Likely
No
No
P9... | SEI CERT C++ Coding Standard > 2 Rules > Rule 05. Characters and Strings (STR) |
cplusplus | 88,046,355 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046355 | 2 | 5 | STR51-CPP | Do not attempt to create a std::string from a null pointer | The
std::basic_string
type uses the
traits
design pattern to handle implementation details of the various string types, resulting in a series of string-like classes with a common, underlying implementation. Specifically, the
std::basic_string
class is paired with
std::char_traits
to create the
std::string
,
std::wstrin... | #include <cstdlib>
#include <string>
void f() {
std::string tmp(std::getenv("TMP"));
if (!tmp.empty()) {
// ...
}
}
## Noncompliant Code Example
In this noncompliant code example, a
std::string
object is created from the results of a call to
std::getenv()
. However, because
std::getenv()
returns a null poi... | #include <cstdlib>
#include <string>
void f() {
const char *tmpPtrVal = std::getenv("TMP");
std::string tmp(tmpPtrVal ? tmpPtrVal : "");
if (!tmp.empty()) {
// ...
}
}
## Compliant Solution
In this compliant solution, the results from the call to
std::getenv()
are checked for null before the
std::string
... | ## Risk Assessment
Dereferencing a null pointer is
undefined behavior
, typically
abnormal program termination
. In some situations, however, dereferencing a null pointer can lead to the execution of arbitrary code [
Jack 2007
,
van Sprundel 2006
]. The indicated severity is for this more severe case; on platforms wher... | SEI CERT C++ Coding Standard > 2 Rules > Rule 05. Characters and Strings (STR) |
cplusplus | 88,046,478 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046478 | 2 | 5 | STR52-CPP | Use valid references, pointers, and iterators to reference elements of a basic_string | Since
std::basic_string
is a container of characters, this rule is a specific instance of
. As a container, it supports iterators just like other containers in the Standard Template Library. However, the
std::basic_string
template class has unusual invalidation semantics. The C++ Standard, [string.require], paragraph 5... | #include <string>
void f(const std::string &input) {
std::string email;
// Copy input into email converting ";" to " "
std::string::iterator loc = email.begin();
for (auto i = input.begin(), e = input.end(); i != e; ++i, ++loc) {
email.insert(loc, *i != ';' ? *i : ' ');
}
}
#include <iostream>
#includ... | #include <string>
void f(const std::string &input) {
std::string email;
// Copy input into email converting ";" to " "
std::string::iterator loc = email.begin();
for (auto i = input.begin(), e = input.end(); i != e; ++i, ++loc) {
loc = email.insert(loc, *i != ';' ? *i : ' ');
}
}
#include <algorithm>
... | ## Risk Assessment
Using an invalid reference, pointer, or iterator to a string object could allow an attacker to run arbitrary code.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
STR52-CPP
High
Probable
No
No
P6
L2
Automated Detection
Tool
Version
Checker
Description
ALLOC.UAF
Use After Free
DF4746, DF... | SEI CERT C++ Coding Standard > 2 Rules > Rule 05. Characters and Strings (STR) |
cplusplus | 88,046,471 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046471 | 2 | 5 | STR53-CPP | Range check element access | The
std::string
index operators
const_reference operator[](size_type) const
and
reference operator[](size_type)
return the character stored at the specified position,
pos
. When
pos >= size()
, a reference to an object of type
charT
with value
charT()
is returned. The index operators are unchecked (no exceptions are th... | #include <string>
extern std::size_t get_index();
void f() {
std::string s("01234567");
s[get_index()] = '1';
}
#include <string>
#include <locale>
void capitalize(std::string &s) {
std::locale loc;
s.front() = std::use_facet<std::ctype<char>>(loc).toupper(s.front());
}
## Noncompliant Code Example
In th... | #include <stdexcept>
#include <string>
extern std::size_t get_index();
void f() {
std::string s("01234567");
try {
s.at(get_index()) = '1';
} catch (std::out_of_range &) {
// Handle error
}
}
#include <string>
extern std::size_t get_index();
void f() {
std::string s("01234567");
std::size_t i = ... | ## Risk Assessment
Unchecked element access can lead to out-of-bound reads and writes and write-anywhere
exploits
. These exploits can, in turn, lead to the execution of arbitrary code with the permissions of the vulnerable process.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
STR53-CPP
High
Unlikely
N... | SEI CERT C++ Coding Standard > 2 Rules > Rule 05. Characters and Strings (STR) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.