Datasets:
language large_stringclasses 1
value | page_id int64 88M 88M | page_url large_stringlengths 73 73 | chapter int64 2 2 | section int64 1 49 | rule_id large_stringlengths 9 9 | title large_stringlengths 21 109 | intro large_stringlengths 321 6.96k | noncompliant_code large_stringlengths 468 8.03k | compliant_solution large_stringlengths 276 8.12k | risk_assessment large_stringlengths 116 1.67k ⌀ | breadcrumb large_stringclasses 11
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
cplusplus | 88,046,461 | https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=88046461 | 2 | 10 | CON50-CPP | Do not destroy a mutex while it is locked | Mutex objects are used to protect shared data from being concurrently accessed. If a mutex object is destroyed while a thread is blocked waiting for the lock,
critical sections
and shared data are no longer protected.
The C++ Standard, [thread.mutex.class], paragraph 5 [
ISO/IEC 14882-2014
], states the following:
The behavior of a program is undefined if it destroys a
mutex
object owned by any thread or a thread terminates while owning a
mutex
object.
Similar wording exists for
std::recursive_mutex
,
std::timed_mutex
,
std::recursive_timed_mutex
, and
std::shared_timed_mutex
. These statements imply that destroying a mutex object while a thread is waiting on it is
undefined behavior
. | #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) {
threads[i] = std::thread(do_work, i, &m);
}
}
## Noncompliant Code Example
This noncompliant code example creates several threads that each invoke the
do_work()
function, passing a unique number as an ID.
Unfortunately, this code contains a race condition, allowing the mutex to be destroyed while it is still owned, because
start_threads()
may invoke the mutex's destructor before all of the threads have exited.
#ffcccc
c
#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) {
threads[i] = std::thread(do_work, i, &m);
}
} | #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[i] = std::thread(do_work, i, &m);
}
}
#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 run_threads() {
std::thread threads[maxThreads];
std::mutex m;
for (size_t i = 0; i < maxThreads; ++i) {
threads[i] = std::thread(do_work, i, &m);
}
for (size_t i = 0; i < maxThreads; ++i) {
threads[i].join();
}
}
## Compliant Solution
## This compliant solution eliminates the race condition by extending the lifetime of the mutex.
#ccccff
c
#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[i] = std::thread(do_work, i, &m);
}
}
## Compliant Solution
## This compliant solution eliminates the race condition by joining the threads before the mutex's destructor is invoked.
#ccccff
c
#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 run_threads() {
std::thread threads[maxThreads];
std::mutex m;
for (size_t i = 0; i < maxThreads; ++i) {
threads[i] = std::thread(do_work, i, &m);
}
for (size_t i = 0; i < maxThreads; ++i) {
threads[i].join();
}
} | ## 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 left in the locked state and no
critical sections
protected by that mutex will be allowed to execute. This is likely to lead to deadlock.
The throwing of an exception must not allow a mutex to remain locked indefinitely. If a mutex was locked and an exception occurs within the critical section protected by that mutex, the mutex must be unlocked as part of exception handling before rethrowing the exception or continuing execution unless subsequent control flow will unlock the mutex.
C++ supplies the lock classes
lock_guard
,
unique_lock
, and
shared_lock
, which can be initialized with a mutex. In its constructor, the lock object locks the mutex, and in its destructor, it unlocks the mutex. The
lock_guard
class provides a simple
RAII
wrapper around a mutex. The
unique_lock
and
shared_lock
classes also use RAII and provide additional functionality, such as manual control over the locking strategy. The
unique_lock
class prevents the lock from being copied, although it allows the lock ownership to be moved to another lock. The
shared_lock
class allows the mutex to be shared by several locks. For all three classes, if an exception occurs and takes control flow out of the scope of the lock, the destructor will unlock the mutex and the program can continue working normally. These lock objects are the preferred way to ensure that a mutex is properly released when an exception is thrown. | #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.
However, if an exception occurs while manipulating the shared data, the mutex will remain locked
.
#ffcccc
c
#include <mutex>
void manipulate_shared_data(std::mutex &pm) {
pm.lock();
// Perform work on shared data.
pm.unlock();
} | #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);
// Perform work on shared data.
}
## Compliant Solution (Manual Unlock)
This compliant solution catches any exceptions thrown when performing work on the shared data and unlocks the mutex before rethrowing the exception.
#ccccff
c
#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
}
## Compliant Solution (Lock Object)
This compliant solution uses a
lock_guard
object to ensure that the mutex will be unlocked, even if an exception occurs, without relying on exception handling machinery and manual resource management.
#ccccff
c
#include <mutex>
void manipulate_shared_data(std::mutex &pm) {
std::lock_guard<std::mutex> lk(pm);
// Perform work on shared data.
} | ## 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 other bit-fields sharing the same byte or word. The problem is difficult to diagnose because it may not be obvious that the same memory location is being modified by multiple threads.
One approach for preventing data races in concurrent programming is to use a mutex. When properly observed by all threads, a mutex can provide safe and secure access to a shared object. However, mutexes provide no guarantees with regard to other objects that might be accessed when the mutex is not controlled by the accessing thread. Unfortunately, there is no portable way to determine which adjacent bit-fields may be stored along with the desired bit-field.
Another approach is to insert a non-bit-field member between any two bit-fields to ensure that each bit-field is the only one accessed within its storage unit. This technique effectively guarantees that no two bit-fields are accessed simultaneously. | 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)
Thread 1: register 0 |= 1 << shift(flag1)
Thread 1: flags = register 0
Thread 2: register 0 |= 2 << shift(flag2)
Thread 2: flags = register 0
## Noncompliant Code Example (bit-field)
Adjacent bit-fields may be stored in a single memory location. Consequently, modifying adjacent bit-fields in different threads is
undefined behavior
, as shown in this noncompliant code example.
#FFcccc
c
struct MultiThreadedFlags {
unsigned int flag1 : 2;
unsigned int flag2 : 2;
};
MultiThreadedFlags flags;
void thread1() {
flags.flag1 = 1;
}
void thread2() {
flags.flag2 = 2;
}
For example, the following instruction sequence is possible.
Thread 1: register 0 = flags
Thread 1: register 0 &= ~mask(flag1)
Thread 2: register 0 = flags
Thread 2: register 0 &= ~mask(flag2)
Thread 1: register 0 |= 1 << shift(flag1)
Thread 1: flags = register 0
Thread 2: register 0 |= 2 << shift(flag2)
Thread 2: flags = register 0 | #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> lk(flags.mutex);
flags.s.flag2 = 2;
}
struct MultiThreadedFlags {
unsigned char flag1;
unsigned char flag2;
};
MultiThreadedFlags flags;
void thread1() {
flags.flag1 = 1;
}
void thread2() {
flags.flag2 = 2;
}
## Compliant Solution (bit-field, C++11 and later, mutex)
## This compliant solution protects all accesses of the flags with a mutex, thereby preventing any data races.
#ccccff
c
#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> lk(flags.mutex);
flags.s.flag2 = 2;
}
## Compliant Solution (C++11)
In this compliant solution, two threads simultaneously modify two distinct non-bit-field members of a structure. Because the members occupy different bytes in memory, no concurrency protection is required.
#ccccff
c
struct MultiThreadedFlags {
unsigned char flag1;
unsigned char flag2;
};
MultiThreadedFlags flags;
void thread1() {
flags.flag1 = 1;
}
void thread2() {
flags.flag2 = 2;
}
Unlike earlier versions of the standard, C++11 and later explicitly define a memory location and provide the following note in [intro.memory] paragraph 4 [
ISO/IEC 14882-2014
]:
[
Note:
Thus a bit-field and an adjacent non-bit-field are in separate memory locations, and therefore can be concurrently updated by two threads of execution without interference. The same applies to two bit-fields, if one is declared inside a nested struct declaration and the other is not, or if the two are separated by a zero-length bit-field declaration, or if they are separated by a non-bit-field declaration. It is not safe to concurrently update two bit-fields in the same struct if all fields between them are also bit-fields of non-zero width. –
end note
]
It is almost certain that
flag1
and
flag2
are stored in the same word. Using a compiler that conforms to earlier versions of the standard, if both assignments occur on a thread-scheduling interleaving that ends with both stores occurring after one another, it is possible that only one of the flags will be set as intended, and the other flag will contain its previous value because both members are represented by the same word, which is the smallest unit the processor can work on. Before the changes made to the C++ Standard for C++11, there were no guarantees that these flags could be modified concurrently. | ## 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 one nonshareable resource must be held.),
hold and wait (A thread must hold a resource while awaiting availability of another resource.),
no preemption (Resources cannot be taken away from a thread while they are in-use.), and
circular wait (A thread must await a resource held by another thread which is, in turn, awaiting a resource held by the first thread.).
Deadlock needs all four conditions, so preventing deadlock requires preventing any one of the four conditions. One simple solution is to lock the mutexes in a predefined order, which prevents circular wait. | #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(BankAccount *from, BankAccount *to, int amount) {
std::lock_guard<std::mutex> from_lock(from->balanceMutex);
// Not enough balance to transfer.
if (from->get_balance() < amount) {
return -1; // Indicate error
}
std::lock_guard<std::mutex> to_lock(to->balanceMutex);
from->set_balance(from->get_balance() - amount);
to->set_balance(to->get_balance() + amount);
return 0;
}
void f(BankAccount *ba1, BankAccount *ba2) {
// Perform the deposits.
std::thread thr1(deposit, ba1, ba2, 100);
std::thread thr2(deposit, ba2, ba1, 100);
thr1.join();
thr2.join();
}
## Noncompliant Code Example
The behavior of this noncompliant code example depends on the runtime environment and the platform's scheduler. The program is susceptible to deadlock if thread
thr1
attempts to lock
ba2
's mutex at the same time thread
thr2
attempts to lock
ba1
's mutex in the
deposit()
function.
#ffcccc
c
#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(BankAccount *from, BankAccount *to, int amount) {
std::lock_guard<std::mutex> from_lock(from->balanceMutex);
// Not enough balance to transfer.
if (from->get_balance() < amount) {
return -1; // Indicate error
}
std::lock_guard<std::mutex> to_lock(to->balanceMutex);
from->set_balance(from->get_balance() - amount);
to->set_balance(to->get_balance() + amount);
return 0;
}
void f(BankAccount *ba1, BankAccount *ba2) {
// Perform the deposits.
std::thread thr1(deposit, ba1, ba2, 100);
std::thread thr2(deposit, ba2, ba1, 100);
thr1.join();
thr2.join();
} | #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 int get_id() const { return id; }
int get_balance() const { return balance; }
void set_balance(int amount) { balance = amount; }
};
std::atomic<unsigned int> BankAccount::globalId(1);
int deposit(BankAccount *from, BankAccount *to, int amount) {
std::mutex *first;
std::mutex *second;
if (from->get_id() == to->get_id()) {
return -1; // Indicate error
}
// Ensure proper ordering for locking.
if (from->get_id() < to->get_id()) {
first = &from->balanceMutex;
second = &to->balanceMutex;
} else {
first = &to->balanceMutex;
second = &from->balanceMutex;
}
std::lock_guard<std::mutex> firstLock(*first);
std::lock_guard<std::mutex> secondLock(*second);
// Check for enough balance to transfer.
if (from->get_balance() >= amount) {
from->set_balance(from->get_balance() - amount);
to->set_balance(to->get_balance() + amount);
return 0;
}
return -1;
}
void f(BankAccount *ba1, BankAccount *ba2) {
// Perform the deposits.
std::thread thr1(deposit, ba1, ba2, 100);
std::thread thr2(deposit, ba2, ba1, 100);
thr1.join();
thr2.join();
}
#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(BankAccount *from, BankAccount *to, int amount) {
// Create lock objects but defer locking them until later.
std::unique_lock<std::mutex> lk1(from->balanceMutex, std::defer_lock);
std::unique_lock<std::mutex> lk2(to->balanceMutex, std::defer_lock);
// Lock both of the lock objects simultaneously.
std::lock(lk1, lk2);
if (from->get_balance() >= amount) {
from->set_balance(from->get_balance() - amount);
to->set_balance(to->get_balance() + amount);
return 0;
}
return -1;
}
void f(BankAccount *ba1, BankAccount *ba2) {
// Perform the deposits.
std::thread thr1(deposit, ba1, ba2, 100);
std::thread thr2(deposit, ba2, ba1, 100);
thr1.join();
thr2.join();
}
## Compliant Solution (Manual Ordering)
This compliant solution eliminates the circular wait condition by establishing a predefined order for locking in the
deposit()
function. Each thread will lock on the basis of the
BankAccount
ID, which is set when the
BankAccount
object is initialized.
#ccccff
c
#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 int get_id() const { return id; }
int get_balance() const { return balance; }
void set_balance(int amount) { balance = amount; }
};
std::atomic<unsigned int> BankAccount::globalId(1);
int deposit(BankAccount *from, BankAccount *to, int amount) {
std::mutex *first;
std::mutex *second;
if (from->get_id() == to->get_id()) {
return -1; // Indicate error
}
// Ensure proper ordering for locking.
if (from->get_id() < to->get_id()) {
first = &from->balanceMutex;
second = &to->balanceMutex;
} else {
first = &to->balanceMutex;
second = &from->balanceMutex;
}
std::lock_guard<std::mutex> firstLock(*first);
std::lock_guard<std::mutex> secondLock(*second);
// Check for enough balance to transfer.
if (from->get_balance() >= amount) {
from->set_balance(from->get_balance() - amount);
to->set_balance(to->get_balance() + amount);
return 0;
}
return -1;
}
void f(BankAccount *ba1, BankAccount *ba2) {
// Perform the deposits.
std::thread thr1(deposit, ba1, ba2, 100);
std::thread thr2(deposit, ba2, ba1, 100);
thr1.join();
thr2.join();
}
## Compliant Solution (std::lock())
This compliant solution uses Standard Template Library facilities to ensure that deadlock does not occur due to circular wait conditions. The
std::lock()
function takes a variable number of lockable objects and attempts to lock them such that deadlock does not occur [
ISO/IEC 14882-2014
]. In typical implementations, this is done by using a combination of
lock()
,
try_lock()
, and
unlock()
to attempt to lock the object and backing off if the lock is not acquired, which may have worse performance than a solution that locks in predefined order explicitly.
#ccccff
c
#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(BankAccount *from, BankAccount *to, int amount) {
// Create lock objects but defer locking them until later.
std::unique_lock<std::mutex> lk1(from->balanceMutex, std::defer_lock);
std::unique_lock<std::mutex> lk2(to->balanceMutex, std::defer_lock);
// Lock both of the lock objects simultaneously.
std::lock(lk1, lk2);
if (from->get_balance() >= amount) {
from->set_balance(from->get_balance() - amount);
to->set_balance(to->get_balance() + amount);
return 0;
}
return -1;
}
void f(BankAccount *ba1, BankAccount *ba2) {
// Perform the deposits.
std::thread thr1(deposit, ba1, ba2, 100);
std::thread thr2(deposit, ba2, ba1, 100);
thr1.join();
thr2.join();
} | ## 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 execution only after it has been notified, generally as the result of the invocation of the
notify_one()
or
notify_all()
member functions invoked by another thread.
The
wait()
function must be invoked from a loop that checks whether a
condition predicate
holds. A condition predicate is an expression constructed from the variables of a function that must be true for a thread to be allowed to continue execution. The thread pauses execution via
wait()
,
wait_for()
,
wait_until()
, or some other mechanism, and is resumed later, presumably when the condition predicate is true and the thread is notified.
#include <condition_variable>
#include <mutex>
extern bool until_finish(void);
extern std::mutex m;
extern std::condition_variable condition;
void func(void) {
std::unique_lock<std::mutex> lk(m);
while (until_finish()) { // Predicate does not hold.
condition.wait(lk);
}
// Resume when condition holds.
}
The notification mechanism notifies the waiting thread and allows it to check its condition predicate. The invocation of
notify_all()
in another thread cannot precisely determine which waiting thread will be resumed. Condition predicate statements allow notified threads to determine whether they should resume upon receiving the notification. | #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) {
condition.wait(lk);
}
// Proceed when condition holds.
}
## Noncompliant Code Example
This noncompliant code example monitors a linked list and assigns one thread to consume list elements when the list is nonempty.
This thread pauses execution using
wait()
and resumes when notified, presumably when the list has elements to be consumed. It is possible for the thread to be notified even if the list is still empty, perhaps because the notifying thread used
notify_all()
, which notifies all threads. Notification using
notify_all()
is frequently preferred over using
notify_one()
. (See
for more information.)
A condition predicate is typically the negation of the condition expression in the loop. In this noncompliant code example, the condition predicate for removing an element from a linked list is
(list->next != nullptr)
, whereas the condition expression for the
while
loop condition is
(list->next == nullptr)
.
This noncompliant code example nests the call to
wait()
inside an
if
block and consequently fails to check the condition predicate after the notification is received. If the notification was spurious or malicious, the thread would wake up prematurely.
#FFcccc
c
#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) {
condition.wait(lk);
}
// Proceed when condition holds.
} | #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);
}
// Proceed when condition holds.
}
#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);
condition.wait(lk, []{ return list.next; });
// Proceed when condition holds.
}
## Compliant Solution (Explicit loop with predicate)
This compliant solution calls the
wait()
member function from within a
while
loop to check the condition both before and after the call to
wait()
.
#ccccff
c
#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);
}
// Proceed when condition holds.
}
## Compliant Solution (Implicit loop with lambda predicate)
The
std::condition_variable::wait()
function has an overloaded form that accepts a function object representing the predicate. This form of
wait()
behaves as if it were implemented as
while (!pred()) wait(lock);
. This compliant solution uses a lambda as a predicate and passes it to the
wait()
function. The predicate is expected to return true when it is safe to proceed, which reverses the predicate logic from the compliant solution using an explicit loop predicate.
#ccccff
c
#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);
condition.wait(lk, []{ return list.next; });
// Proceed when condition holds.
}
Risk Assessment
Failure to enclose calls to the
wait()
,
wait_for()
, or
wait_until()
member functions inside a
while
loop can lead to indefinite blocking and
denial of service
(DoS).
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CON54-CPP
Low
Unlikely
Yes
No
P2
L3 | 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; for example, there is no deadlock.
Condition variables must be used inside a
while
loop. (See
for more information.) To guarantee liveness, programs must test the
while
loop condition before invoking the
condition_variable::wait()
member function. This early test checks whether another thread has already satisfied the
condition predicate
and has sent a notification. Invoking
wait()
after the notification has been sent results in indefinite blocking.
To guarantee thread safety, programs must test the
while
loop condition after returning from
wait()
. When a given thread invokes
wait()
, it will attempt to block until its condition variable is signaled by a call to
condition_variable::notify_all()
or to
condition_variable::notify_one()
.
The
notify_one()
member function unblocks one of the threads that are blocked on the specified condition variable at the time of the call. If multiple threads are waiting on the same condition variable, the scheduler can select any of those threads to be awakened (assuming that all threads have the same priority level).
The
notify_all()
member function unblocks all of the threads that are blocked on the specified condition variable at the time of the call. The order in which threads execute following a call to
notify_all()
is unspecified. Consequently, an unrelated thread could start executing, discover that its condition predicate is satisfied, and resume execution even though it was supposed to remain dormant.
For these reasons, threads must check the condition predicate after the
wait()
function returns. A
while
loop is the best choice for checking the condition predicate both before and after invoking
wait()
.
The use of
notify_one()
is safe if each thread uses a unique condition variable. If multiple threads share a condition variable, the use of
notify_one()
is safe only if the following conditions are met:
All threads must perform the same set of operations after waking up, which means that any thread can be selected to wake up and resume for a single invocation of
notify_one()
.
Only one thread is required to wake upon receiving the signal.
The
notify_all()
function can be used to unblock all of the threads that are blocked on the specified condition variable if the use of
notify_one()
is unsafe. | #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 (currentStep != myStep) {
std::cout << "Thread " << myStep << " is sleeping..." << std::endl;
cond.wait(lk);
std::cout << "Thread " << myStep << " woke up" << std::endl;
}
// Do processing...
std::cout << "Thread " << myStep << " is processing..." << std::endl;
currentStep++;
// Signal awaiting task.
cond.notify_one();
std::cout << "Thread " << myStep << " is exiting..." << std::endl;
}
int main() {
constexpr size_t numThreads = 5;
std::thread threads[numThreads];
// Create threads.
for (size_t i = 0; i < numThreads; ++i) {
threads[i] = std::thread(run_step, i);
}
// Wait for all threads to complete.
for (size_t i = numThreads; i != 0; --i) {
threads[i - 1].join();
}
}
## Noncompliant Code Example (notify_one())
This noncompliant code example uses five threads that are intended to execute sequentially according to the step level assigned to each thread when it is created (serialized processing). The
currentStep
variable holds the current step level and is incremented when the respective thread completes. Finally, another thread is signaled so that the next step can be executed. Each thread waits until its step level is ready, and the
wait()
call is wrapped inside a
while
loop, in compliance with
CON54-CPP. Wrap functions that can spuriously wake up in a loop.
#FFcccc
c
#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 (currentStep != myStep) {
std::cout << "Thread " << myStep << " is sleeping..." << std::endl;
cond.wait(lk);
std::cout << "Thread " << myStep << " woke up" << std::endl;
}
// Do processing...
std::cout << "Thread " << myStep << " is processing..." << std::endl;
currentStep++;
// Signal awaiting task.
cond.notify_one();
std::cout << "Thread " << myStep << " is exiting..." << std::endl;
}
int main() {
constexpr size_t numThreads = 5;
std::thread threads[numThreads];
// Create threads.
for (size_t i = 0; i < numThreads; ++i) {
threads[i] = std::thread(run_step, i);
}
// Wait for all threads to complete.
for (size_t i = numThreads; i != 0; --i) {
threads[i - 1].join();
}
}
In this example, all threads share a single condition variable. Each thread has its own distinct condition predicate because each thread requires
currentStep
to have a different value before proceeding. When the condition variable is signaled, any of the waiting threads can wake up. The following table illustrates a possible scenario in which the liveness property is violated. If, by chance, the notified thread is not the thread with the next step value, that thread will wait again. No additional notifications can occur, and eventually the pool of available threads will be exhausted.
Deadlock: Out-of-Sequence Step Value
Time
Thread #
(
my_step
)
current_step
Action
0
3
0
Thread 3 executes the first time: the predicate is
false -> wait()
1
2
0
Thread 2 executes the first time: the predicate is
false -> wait()
2
4
0
Thread 4 executes the first time: the predicate is
false -> wait()
3
0
0
Thread 0 executes the first time: the predicate is
true -> currentStep++; notify_one()
4
1
1
Thread 1 executes the first time: the predicate is
true -> currentStep++; notify_one()
5
3
2
Thread 3 wakes up (scheduler choice): the predicate is
false -> wait()
6
—
—
Thread exhaustion!
There are no more threads to run, and a conditional variable signal is needed to wake up the others.
## This noncompliant code example violates the liveness property. | #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 (currentStep != myStep) {
std::cout << "Thread " << myStep << " is sleeping..." << std::endl;
cond.wait(lk);
std::cout << "Thread " << myStep << " woke up" << std::endl;
}
// Do processing ...
std::cout << "Thread " << myStep << " is processing..." << std::endl;
currentStep++;
// Signal ALL waiting tasks.
cond.notify_all();
std::cout << "Thread " << myStep << " is exiting..." << std::endl;
}
// ... main() unchanged ...
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
constexpr size_t numThreads = 5;
std::mutex mutex;
std::condition_variable cond[numThreads];
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 (currentStep != myStep) {
std::cout << "Thread " << myStep << " is sleeping..." << std::endl;
cond[myStep].wait(lk);
std::cout << "Thread " << myStep << " woke up" << std::endl;
}
// Do processing ...
std::cout << "Thread " << myStep << " is processing..." << std::endl;
currentStep++;
// Signal next step thread.
if ((myStep + 1) < numThreads) {
cond[myStep + 1].notify_one();
}
std::cout << "Thread " << myStep << " is exiting..." << std::endl;
}
// ... main() unchanged ...
## Compliant Solution (notify_all())
This compliant solution uses
notify_all()
to signal all waiting threads instead of a single random thread. Only the
run_step()
thread code from the noncompliant code example is modified.
#ccccff
c
#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 (currentStep != myStep) {
std::cout << "Thread " << myStep << " is sleeping..." << std::endl;
cond.wait(lk);
std::cout << "Thread " << myStep << " woke up" << std::endl;
}
// Do processing ...
std::cout << "Thread " << myStep << " is processing..." << std::endl;
currentStep++;
// Signal ALL waiting tasks.
cond.notify_all();
std::cout << "Thread " << myStep << " is exiting..." << std::endl;
}
// ... main() unchanged ...
Awakening all threads guarantees the liveness property because each thread will execute its condition predicate test, and exactly one will succeed and continue execution.
## Compliant Solution (Usingnotify_one()with a Unique Condition Variable per Thread)
Another compliant solution is to use a unique condition variable for each thread (all associated with the same mutex). In this case,
notify_one()
wakes up only the thread that is waiting on it.
This solution is more efficient than using
notify_all()
because only the desired thread is awakened.
The condition predicate of the signaled thread must be true; otherwise, a deadlock will occur.
#ccccff
c
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
constexpr size_t numThreads = 5;
std::mutex mutex;
std::condition_variable cond[numThreads];
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 (currentStep != myStep) {
std::cout << "Thread " << myStep << " is sleeping..." << std::endl;
cond[myStep].wait(lk);
std::cout << "Thread " << myStep << " woke up" << std::endl;
}
// Do processing ...
std::cout << "Thread " << myStep << " is processing..." << std::endl;
currentStep++;
// Signal next step thread.
if ((myStep + 1) < numThreads) {
cond[myStep + 1].notify_one();
}
std::cout << "Thread " << myStep << " is exiting..." << std::endl;
}
// ... main() unchanged ... | ## 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 recursive mutex may be locked recursively by the thread that currently owns the mutex. All mutex classes support the ability to speculatively lock the mutex through functions such as
try_lock()
,
try_lock_for()
,
try_lock_until()
,
try_lock_shared_for()
, and
try_lock_shared_until()
. These speculative locking functions attempt to obtain ownership of the mutex for the calling thread, but will not block in the event the ownership cannot be obtained. Instead, they return a Boolean value specifying whether the ownership of the mutex was obtained or not.
The C++ Standard, [thread.mutex.requirements.mutex], paragraphs 14 and 15 [
ISO/IEC 14882-2014
], state the following:
The expression
m.try_lock()
shall be well-formed and have the following semantics:
Requires: If
m
is of type
std::mutex
,
std::timed_mutex
, or
std::shared_timed_mutex
, the calling thread does not own the mutex.
Further,
[thread.timedmutex.class], paragraph 3, in part, states the following:
The behavior of a program is undefined if:
— a thread that owns a
timed_mutex
object calls
lock()
,
try_lock()
,
try_lock_for()
, or
try_lock_until()
on that object
Finally, [thread.sharedtimedmutex.class], paragraph 3, in part, states the following:
The behavior of a program is undefined if:
— a thread attempts to recursively gain any ownership of a
shared_timed_mutex
.
Thus, attempting to speculatively lock a non-recursive mutex object that is already owned by the calling thread is
undefined behavior
. Do not call
try_lock()
,
try_lock_for()
,
try_lock_until()
,
try_lock_shared_for()
, or
try_lock_shared_until()
on a non-recursive mutex object from a thread that already owns that mutex object. | #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 mutex.
catch (...) {
m.unlock();
throw;
}
m.unlock();
}
void start_func() {
std::lock_guard<std::mutex> lock(m);
do_work();
}
int main() {
std::thread t(start_func);
do_work();
t.join();
}
## Noncompliant Code Example
In this noncompliant code example, the mutex
m
is locked by the thread's initial entry point and is speculatively locked in the
do_work()
function from the same thread, resulting in undefined behavior because it is not a recursive mutex. With common implementations, this may result in
deadlock
.
#ffcccc
c
#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 mutex.
catch (...) {
m.unlock();
throw;
}
m.unlock();
}
void start_func() {
std::lock_guard<std::mutex> lock(m);
do_work();
}
int main() {
std::thread t(start_func);
do_work();
t.join();
} | #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 mutex.
catch (...) {
m.unlock();
throw;
}
m.unlock();
}
void start_func() {
do_work();
}
int main() {
std::thread t(start_func);
do_work();
t.join();
}
## Compliant Solution
This compliant solution removes the lock from the thread's initial entry point, allowing the mutex to be speculatively locked, but not recursively.
#ccccff
c
#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 mutex.
catch (...) {
m.unlock();
throw;
}
m.unlock();
}
void start_func() {
do_work();
}
int main() {
std::thread t(start_func);
do_work();
t.join();
} | ## 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()) {
// Handle error
return;
}
table[pos] = value;
}
#include <iterator>
template <typename ForwardIterator>
void f_imp(ForwardIterator b, ForwardIterator e, int val, std::forward_iterator_tag) {
do {
*b++ = val;
} while (b != e);
}
template <typename ForwardIterator>
void f(ForwardIterator b, ForwardIterator e, int val) {
typename std::iterator_traits<ForwardIterator>::iterator_category cat;
f_imp(b, e, val, cat);
}
## Noncompliant Code Example (Pointers)
This noncompliant code example shows a function,
insert_in_table()
, that has two
int
parameters,
pos
and
value
, both of which can be influenced by data originating from untrusted sources. The function performs a range check to ensure that
pos
does not exceed the upper bound of the array, specified by
tableSize
, but fails to check the lower bound. Because
pos
is declared as a (signed)
int
, this parameter can assume a negative value, resulting in a write outside the bounds of the memory referenced by
table
.
#ffcccc
cpp
#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;
}
## Noncompliant Code Example (std::vector)
In this noncompliant code example, a
std::vector
is used in place of a pointer and size pair. The function performs a range check to ensure that
pos
does not exceed the upper bound of the container. Because
pos
is declared as a (signed)
long long
, this parameter can assume a negative value. On systems where
std::vector::size_type
is ultimately implemented as an
unsigned int
(such as with
Microsoft Visual Studio
2013), the usual arithmetic conversions applied for the comparison expression will convert the unsigned value to a signed value. If
pos
has a negative value, this comparison will not fail, resulting in a write outside the bounds of the
std::vector
object when the negative value is interpreted as a large unsigned value in the indexing operator.
#ffcccc
cpp
#include <vector>
void insert_in_table(std::vector<int> &table, long long pos, int value) {
if (pos >= table.size()) {
// Handle error
return;
}
table[pos] = value;
}
## Noncompliant Code Example (Iterators)
true
This example could use an xref to some (TBD) guideline about type-safe template meta-programming. That would explain the extra efforts involving
f_imp()
.
In this noncompliant code example, the
f_imp()
function is given the (correct) ending iterator
e
for a container, and
b
is an iterator from the same container. However, it is possible that
b
is not within the valid range of its container. For instance, if the container were empty,
b
would equal
e
and be improperly dereferenced.
#ffcccc
cpp
#include <iterator>
template <typename ForwardIterator>
void f_imp(ForwardIterator b, ForwardIterator e, int val, std::forward_iterator_tag) {
do {
*b++ = val;
} while (b != e);
}
template <typename ForwardIterator>
void f(ForwardIterator b, ForwardIterator e, int val) {
typename std::iterator_traits<ForwardIterator>::iterator_category cat;
f_imp(b, e, val, cat);
} | #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
if (pos >= tableSize) {
// Handle error
return;
}
table[pos] = value;
}
template <std::size_t N>
void insert_in_table(int (&table)[N], std::size_t pos, int value) { // #2
insert_in_table(table, N, pos, value);
}
void f() {
// Exposition only
int table1[100];
int *table2 = new int[100];
insert_in_table(table1, 0, 0); // Calls #2
insert_in_table(table2, 0, 0); // Error, no matching function call
insert_in_table(table1, 100, 0, 0); // Calls #1
insert_in_table(table2, 100, 0, 0); // Calls #1
delete [] table2;
}
#include <vector>
void insert_in_table(std::vector<int> &table, std::size_t pos, int value) {
if (pos >= table.size()) {
// Handle error
return;
}
table[pos] = value;
}
#include <vector>
void insert_in_table(std::vector<int> &table, std::size_t pos, int value) noexcept(false) {
table.at(pos) = value;
}
#include <iterator>
template <typename ForwardIterator>
void f_imp(ForwardIterator b, ForwardIterator e, int val, std::forward_iterator_tag) {
while (b != e) {
*b++ = val;
}
}
template <typename ForwardIterator>
void f(ForwardIterator b, ForwardIterator e, int val) {
typename std::iterator_traits<ForwardIterator>::iterator_category cat;
f_imp(b, e, val, cat);
}
## Compliant Solution (size_t)
## In this compliant solution, the parameterposis declared assize_t, which prevents the passing of negative arguments.
#ccccff
cpp
#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;
}
## Compliant Solution (Non-Type Templates)
true
I think this CS should be removed as it doesn't really add much benefit to this discussion. It seems like it would be a far better fit as a recommendation in DCL to declare functions accepting pointer/size (array) to have a non-type template overload where the array size is deduced automatically.
If we picked a more convincing NCCE, it might make sense to include a CS of this type here.
Non-type templates can be used to define functions accepting an array type where the array bounds are deduced at compile time. This compliant solution is functionally equivalent to the previous bounds-checking one except that it additionally supports calling
insert_in_table()
with an array of known bounds.
#ccccff
cpp
#include <cstddef>
#include <new>
void insert_in_table(int *table, std::size_t tableSize, std::size_t pos, int value) { // #1
if (pos >= tableSize) {
// Handle error
return;
}
table[pos] = value;
}
template <std::size_t N>
void insert_in_table(int (&table)[N], std::size_t pos, int value) { // #2
insert_in_table(table, N, pos, value);
}
void f() {
// Exposition only
int table1[100];
int *table2 = new int[100];
insert_in_table(table1, 0, 0); // Calls #2
insert_in_table(table2, 0, 0); // Error, no matching function call
insert_in_table(table1, 100, 0, 0); // Calls #1
insert_in_table(table2, 100, 0, 0); // Calls #1
delete [] table2;
}
## Compliant Solution (std::vector,size_t)
In this compliant solution, the parameter
pos
is declared as
size_t
, which ensures that the comparison expression will fail when a large, positive value (converted from a negative argument) is given.
#ccccff
cpp
#include <vector>
void insert_in_table(std::vector<int> &table, std::size_t pos, int value) {
if (pos >= table.size()) {
// Handle error
return;
}
table[pos] = value;
}
## Compliant Solution (std::vector::at())
In this compliant solution, access to the vector is accomplished with the
at()
method. This method provides bounds checking, throwing a
std::out_of_range
exception if
pos
is not a valid index value. The
insert_in_table()
function is declared with
noexcept(false)
in compliance with
.
#ccccff
cpp
#include <vector>
void insert_in_table(std::vector<int> &table, std::size_t pos, int value) noexcept(false) {
table.at(pos) = value;
}
## Compliant Solution
## This compliant solution tests for iterator validity before attempting to dereferenceb.
#ccccff
cpp
#include <iterator>
template <typename ForwardIterator>
void f_imp(ForwardIterator b, ForwardIterator e, int val, std::forward_iterator_tag) {
while (b != e) {
*b++ = val;
}
}
template <typename ForwardIterator>
void f(ForwardIterator b, ForwardIterator e, int val) {
typename std::iterator_traits<ForwardIterator>::iterator_category cat;
f_imp(b, e, val, cat);
} | ## 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 reference. Storing an iterator, reference, or pointer to an element within a container for any length of time comes with a risk that the underlying container may be modified such that the stored iterator, pointer, or reference becomes invalid. For instance, when a sequence container such as
std::vector
requires an underlying reallocation, outstanding iterators, pointers, and references will be invalidated [
Kalev 99
]. Use only a
valid pointer
, reference, or iterator to refer to an element of a container.
The C++ Standard, [container.requirements.general], paragraph 12
[
ISO/IEC 14882-2014
] states the following:
Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container.
The C++ Standard allows references and pointers to be invalidated independently for the same operation, which may result in an invalidated reference but not an invalidated pointer. However, relying on this distinction is insecure because the object pointed to by the pointer may be different than expected even if the pointer is valid. For instance, it is possible to retrieve a pointer to an element from a container, erase that element (invalidating references when destroying the underlying object), then insert a new element at the same location within the container causing the extant pointer to now point to a valid, but distinct object. Thus, any operation that invalidates a pointer or a reference should be treated as though it invalidates both pointers and references.
The following container functions can invalidate iterators, references, and pointers under certain circumstances.
Class
Function
Iterators
References/Pointers
Notes
std::deque
insert()
,
emplace_front()
,
emplace_back()
,
emplace()
,
push_front()
,
push_back()
X
X
An insertion in the middle of the deque invalidates all the iterators and references to elements of the deque. An insertion at either end of the deque invalidates all the iterators to the deque but has no effect on the validity of references to elements of the deque. ([deque.modifiers], paragraph 1
)
erase()
,
pop_back()
,
resize()
X
X
An erase operation that erases the last element of a deque invalidates only the past-the-end iterator and all iterators and references to the erased elements. An erase operation that erases the first element of a deque but not the last element invalidates only the erased elements. An erase operation that erases neither the first element nor the last element of a deque invalidates the past-the-end iterator and all iterators and references to all the elements of the deque.
([deque.modifiers], paragraph 4)
clear()
X
X
Destroys all elements in the container. Invalidates all references, pointers, and iterators referring to the elements of the container and may invalidate the past-the-end iterator. ([sequence.reqmts], Table 100)
std::forward_list
erase_after()
,
pop_front()
,
resize()
X
X
erase_after
shall invalidate only iterators and references to the erased elements. ([forwardlist.modifiers], paragraph 1)
remove()
,
unique()
X
X
Invalidates only the iterators and references to the erased elements. ([forwardlist.ops], paragraph 12 & paragraph 16)
clear()
X
X
Destroys all elements in the container. Invalidates all
references, pointers, and iterators referring to
the elements of the container and may invalidate the
past-the-end iterator. (
[sequence.reqmts], Table 100)
std::list
erase()
,
pop_front()
,
pop_back()
,
clear()
,
remove()
,
remove_if()
,
unique()
X
X
Invalidates only the iterators and references to the erased elements. ([list.modifiers], paragraph 3 and [list.ops], paragraph 15 & paragraph 19)
clear()
X
X
Destroys all elements in the container. Invalidates all
references, pointers, and iterators referring to
the elements of the container and may invalidate the
past-the-end iterator. (
[sequence.reqmts], Table 100)
std::vector
reserve()
X
X
After
reserve()
,
capacity()
is greater or equal to the argument of
reserve
if reallocation happens and is equal to the previous value of
capacity()
otherwise. Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. ([vector.capacity], paragraph 3 & paragraph 6)
insert()
,
emplace_back()
,
emplace()
,
push_back()
X
X
Causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid. ([vector.modifiers], paragraph 1). All iterators and references after the insertion point are invalidated.
erase()
,
pop_back()
,
resize()
X
X
Invalidates iterators and references at or after the point of the erase. (
[vector.modifiers], paragraph 3)
clear()
X
X
Destroys all elements in the container. Invalidates all
references, pointers, and iterators referring to
the elements of the container and may invalidate the
past-the-end iterator. (
[sequence.reqmts], Table 100)
std::set
,
std::multiset
,
std::map
,
std::multimap
erase()
,
clear()
X
X
Invalidates only iterators and references to the erased elements. ([associative.reqmts], paragraph 9)
std::unordered_set
,
std::unordered_multiset
,
std::unordered_map
,
std::unordered_multimap
erase()
,
clear()
X
X
Invalidates only iterators and references to the erased elements. ([unord.req], paragraph 14)
insert()
,
emplace()
X
The
insert
and
emplace
members shall not affect the validity of iterators if (
N
+
n
) <
z
*
B
, where
N
is the number of elements in the container prior to the
insert
operation,
n
is the number of elements inserted,
B
is the container’s bucket count, and
z
is the container’s maximum load factor.
([unord.req], paragraph 15)
rehash()
,
reserve()
X
Rehashing invalidates iterators, changes ordering between elements, and changes which buckets the elements appear in but does not invalidate pointers or references to elements.
([unord.req], paragraph 9)
std::valarray
resize()
X
Resizing invalidates all pointers and references to elements in the array. ([valarray.members], paragraph 12)
A
std::basic_string
object is also a container to which this rule applies. For more specific information pertaining to
std::basic_string
containers, see
. | #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
insert()
, and subsequent loop iterations have
undefined behavior
.
#FFcccc
cpp
#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);
}
} | #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 count) {
std::deque<double> d;
std::transform(items, items + count, std::inserter(d, d.begin()),
[](double d) { return d + 41.0; });
}
## Compliant Solution (Updated Iterator)
## In this compliant solution,posis assigned a valid iterator on each insertion, preventing undefined behavior.
#ccccff
cpp
#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);
}
}
## Compliant Solution (Generic Algorithm)
This compliant solution replaces the handwritten loop with the generic standard template library algorithm
std::transform()
. The call to
std::transform()
accepts the range of elements to transform, the location to store the transformed values (which, in this case, is a
std::inserter
object to insert them at the beginning of
d
), and the transformation function to apply (which, in this case, is a simple lambda).
#ccccff
cpp
#include <algorithm>
#include <deque>
#include <iterator>
void f(const double *items, std::size_t count) {
std::deque<double> d;
std::transform(items, items + count, std::inserter(d, d.begin()),
[](double d) { return d + 41.0; });
} | ## 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.UAF
Use After Free
DF4746, DF4747, DF4748, DF4749
ITER.CONTAINER.MODIFIED
Parasoft C/C++test
CERT_CPP-CTR51-a
Do not modify container while iterating over it
CERT C++: CTR51-CPP
Checks for use of invalid iterator (rule partially covered).
PVS-Studio
V783
Related Vulnerabilities
Search for
vulnerabilities
resulting from the violation of this rule on the
CERT website
. | 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 hold the data to be copied.
Vulnerabilities
that result from copying data to an undersized buffer can also involve null-terminated strings. Consult
for specific examples of this rule that involve strings.
Copies can be made with the
std::memcpy()
function. However, the
std::memmove()
and
std::memset()
functions can also have the same vulnerabilities because they overwrite a block of memory without checking that the block is valid. Such issues are not limited to C standard library functions; standard template library (STL) generic algorithms, such as
std::copy()
,
std::fill()
, and
std::transform()
, also assume valid output buffer sizes [
ISO/IEC 14882-2014
]. | #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 containers can be subject to the same vulnerabilities as array data types. The
std::copy()
algorithm provides no inherent bounds checking and can lead to a buffer overflow. In this noncompliant code example, a vector of integers is copied from
src
to
dest
using
std::copy()
. Because
std::copy()
does nothing to expand the
dest
vector, the program will overflow the buffer on copying the first element.
#FFCCCC
cpp
#include <algorithm>
#include <vector>
void f(const std::vector<int> &src) {
std::vector<int> dest;
std::copy(src.begin(), src.end(), dest.begin());
// ...
}
This hazard applies to any algorithm that takes a destination iterator, expecting to fill it with values. Most of the STL algorithms expect the destination container to have sufficient space to hold the values provided.
## Noncompliant Code Example
In this noncompliant code example,
std::fill_n()
is used to fill a buffer with 10 instances of the value
0x42
. However, the buffer has not allocated any space for the elements, so this operation results in a buffer overflow.
#FFCCCC
cpp
#include <algorithm>
#include <vector>
void f() {
std::vector<int> v;
std::fill_n(v.begin(), 10, 0x42);
} | #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::vector<int> &src) {
std::vector<int> dest;
std::copy(src.begin(), src.end(), std::back_inserter(dest));
// ...
}
#include <vector>
void f(const std::vector<int> &src) {
std::vector<int> dest(src);
// ...
}
#include <algorithm>
#include <vector>
void f() {
std::vector<int> v(10);
std::fill_n(v.begin(), 10, 0x42);
}
#include <algorithm>
#include <vector>
void f() {
std::vector<int> v(10, 0x42);
}
## Compliant Solution (Sufficient Initial Capacity)
The proper way to use
std::copy()
is to ensure the destination container can hold all the elements being copied to it. This compliant solution enlarges the capacity of the vector prior to the copy operation.
#ccccff
cpp
#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());
// ...
}
## Compliant Solution (Per-Element Growth)
An alternative approach is to supply a
std::back_insert_iterator
as the destination argument. This iterator expands the destination container by one element for each element supplied by the algorithm, which guarantees the destination container will become sufficiently large to hold the elements provided.
#ccccff
cpp
#include <algorithm>
#include <iterator>
#include <vector>
void f(const std::vector<int> &src) {
std::vector<int> dest;
std::copy(src.begin(), src.end(), std::back_inserter(dest));
// ...
}
## Compliant Solution (Assignment)
## The simplest solution is to constructdestfromsrcdirectly, as in this compliant solution.
#ccccff
cpp
#include <vector>
void f(const std::vector<int> &src) {
std::vector<int> dest(src);
// ...
}
## Compliant Solution (Sufficient Initial Capacity)
## This compliant solution ensures the capacity of the vector is sufficient before attempting to fill the container.
#ccccff
cpp
#include <algorithm>
#include <vector>
void f() {
std::vector<int> v(10);
std::fill_n(v.begin(), 10, 0x42);
}
However, this compliant solution is inefficient. The constructor will default-construct 10 elements of type
int
, which are subsequently replaced by the call to
std::fill_n()
, meaning that each element in the container is initialized twice.
## Compliant Solution (Fill Initialization)
## This compliant solution initializesvto 10 elements whose values are all0x42.
#ccccff
cpp
#include <algorithm>
#include <vector>
void f() {
std::vector<int> v(10, 0x42);
} | ## 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 container.
The iterator representing the start of the range precedes the iterator representing the end of the range.
The iterators are not invalidated, in conformance with
.
An empty iterator range (where the two iterators are valid and equivalent) is considered to be valid.
Using a range of two iterators that are invalidated or do not refer into the same container results in
undefined behavior
. | #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.begin(), e, [](int i) { std::cout << i; });
}
## Noncompliant Code Example
In this noncompliant example, the two iterators that delimit the range point into the same container, but the first iterator does not precede the second. On each iteration of its internal loop,
std::for_each()
compares the first iterator (after incrementing it) with the second for equality; as long as they are not equal, it will continue to increment the first iterator. Incrementing the iterator representing the past-the-end element of the range results in
undefined behavior
.
#FFcccc
cpp
#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; });
}
Invalid iterator ranges can also result from comparison functions that return true for equal values. See
for more information about comparators.
## Noncompliant Code Example
In this noncompliant code example, iterators from different containers are passed for the same iterator range. Although many STL
implementations
will compile this code and the program may behave as the developer expects, there is no requirement that an STL implementation treat a default-initialized iterator as a synonym for the iterator returned by
end()
.
#FFcccc
cpp
#include <algorithm>
#include <iostream>
#include <vector>
void f(const std::vector<int> &c) {
std::vector<int>::const_iterator e;
std::for_each(c.begin(), e, [](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::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::cout << i; });
}
## Compliant Solution
## In this compliant solution, the iterator values passed tostd::for_each()are passed in the proper order.
#ccccff
cpp
#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; });
}
## Compliant Solution
## In this compliant solution, the proper iterator generated by a call toend()is passed.
#ccccff
cpp
#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; });
} | ## 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_dereference
LANG.MEM.BO
Buffer Overrun
C++3802
Parasoft C/C++test
CERT_CPP-CTR53-a
CERT_CPP-CTR53-b
Do not use an iterator range that isn't really a range
Do not compare iterators from different containers
CERT C++: CTR53-CPP
Checks for invalid iterator range (rule partially covered).
PVS-Studio
V539
,
V662
,
V789
Related Vulnerabilities
In
Fun with erase()
, Chris Rohlf discusses the exploit potential of a program that calls
vector::erase()
with invalid iterator ranges [
Rohlf 2009
].
Search for
vulnerabilities
resulting from the violation of this rule on the
CERT website
. | 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 to the same container object or must be obtained via a call to
end()
(or
cend()
) on the same container object.
If two unrelated iterators (including pointers) are subtracted, the operation results in
undefined behavior
[
ISO/IEC 14882-2014
]
. Do not subtract two iterators (including pointers) unless both point into the same container or one past the end of the same container. | #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 <iostream>
template <typename Ty>
bool in_range(const Ty *test, const Ty *r, size_t n) {
return test >= r && test < (r + n);
}
void f() {
double foo[10];
double *x = &foo[0];
double bar;
std::cout << std::boolalpha << in_range(&bar, x, 10);
}
#include <iostream>
#include <iterator>
#include <vector>
template <typename RandIter>
bool in_range_impl(RandIter test, RandIter r_begin, RandIter r_end, std::random_access_iterator_tag) {
return test >= r_begin && test < r_end;
}
template <typename Iter>
bool in_range(Iter test, Iter r_begin, Iter r_end) {
typename std::iterator_traits<Iter>::iterator_category cat;
return in_range_impl(test, r_begin, r_end, cat);
}
void f() {
std::vector<double> foo(10);
std::vector<double> bar(1);
std::cout << std::boolalpha << in_range(bar.begin(), foo.begin(), foo.end());
}
#include <functional>
#include <iostream>
template <typename Ty>
bool in_range(const Ty *test, const Ty *r, size_t n) {
std::less<const Ty *> less;
return !less(test, r) && less(test, r + n);
}
void f() {
double foo[10];
double *x = &foo[0];
double bar;
std::cout << std::boolalpha << in_range(&bar, x, 10);
}
## Noncompliant Code Example
This noncompliant code example attempts to determine whether the
pointer
test
is within the range
[r, r + n]
. However, when
test
does not point within the given range, as in this example, the subtraction produces undefined behavior.
#ffcccc
cpp
#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);
}
## Noncompliant Code Example
In this noncompliant code example, the
in_range()
function is implemented using a comparison expression instead of subtraction. The C++ Standard, [expr.rel], paragraph 4 [
ISO/IEC 14882-2014
], states the following:
If two operands
p
and
q
compare equal,
p<=q
and
p>=q
both yield
true
and
p<q
and
p>q
both yield
false
. Otherwise, if a pointer
p
compares greater than a pointer
q
,
p>=q
,
p>q
,
q<=p
, and
q<p
all yield
true
and
p<=q
,
p<q
,
q>=p
, and
q>p
all yield
false
. Otherwise, the result of each of the operators is unspecified.
true
The "Thus" statement below is incomplete. What is required to make such a statement is p3, which is a total mess because it doesn't say WHAT should happen when two pointers not of the same container are compared. The assumption is that this is what causes us to fall into the final "otherwise" clause of p4, but I think a core issue may be in order. Once that is resolved, we can update this section accordingly.
Thus, comparing two pointers that do not point into the same container or one past the end of the container results in
unspecified behavior
. Although the following example is an improvement over the previous noncompliant code example, it does not result in portable code and may fail when executed on a segmented memory architecture (such as some antiquated x86 variants). Consequently, it is noncompliant.
#ffcccc
cpp
#include <iostream>
template <typename Ty>
bool in_range(const Ty *test, const Ty *r, size_t n) {
return test >= r && test < (r + n);
}
void f() {
double foo[10];
double *x = &foo[0];
double bar;
std::cout << std::boolalpha << in_range(&bar, x, 10);
}
## Noncompliant Code Example
This noncompliant code example is roughly equivalent to the previous example, except that it uses iterators in place of raw pointers. As with the previous example, the
in_range_impl()
function exhibits
unspecified behavior
when the iterators do not refer into the same container because the operational semantics of
a < b
on a random access iterator are
b - a > 0
, and
>=
is implemented in terms of
<
.
#ffcccc
cpp
#include <iostream>
#include <iterator>
#include <vector>
template <typename RandIter>
bool in_range_impl(RandIter test, RandIter r_begin, RandIter r_end, std::random_access_iterator_tag) {
return test >= r_begin && test < r_end;
}
template <typename Iter>
bool in_range(Iter test, Iter r_begin, Iter r_end) {
typename std::iterator_traits<Iter>::iterator_category cat;
return in_range_impl(test, r_begin, r_end, cat);
}
void f() {
std::vector<double> foo(10);
std::vector<double> bar(1);
std::cout << std::boolalpha << in_range(bar.begin(), foo.begin(), foo.end());
}
## Noncompliant Code Example
In this noncompliant code example,
std::less<>
is used in place of the
<
operator. The C++ Standard, [comparisons], paragraph 14 [
ISO/IEC 14882-2014
], states the following:
For templates
greater
,
less
,
greater_equal
, and
less_equal
, the specializations for any pointer type yield a total order, even if the built-in operators
<
,
>
,
<=
,
>=
do not.
Although this approach yields a total ordering, the definition of that total ordering is still unspecified by the
implementation
. For instance, the following statement could result in the assertion triggering for a given, unrelated pair of pointers,
a
and
b
:
assert(std::less<T *>()(a, b) == std::greater<T *>()(a, b));
. Consequently, this noncompliant code example is still nonportable and, on common implementations of
std::less<>
, may even result in
undefined behavior
when the
<
operator is invoked.
#ffcccc
cpp
#include <functional>
#include <iostream>
template <typename Ty>
bool in_range(const Ty *test, const Ty *r, size_t n) {
std::less<const Ty *> less;
return !less(test, r) && less(test, r + n);
}
void f() {
double foo[10];
double *x = &foo[0];
double bar;
std::cout << std::boolalpha << in_range(&bar, x, 10);
} | #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) {
if (cur == testPtr) {
return true;
}
}
return false;
}
void f() {
double foo[10];
double *x = &foo[0];
double bar;
std::cout << std::boolalpha << in_range(&bar, x, 10);
}
## Compliant Solution
This compliant solution demonstrates a fully portable, but likely inefficient, implementation of
in_range()
that compares
test
against each possible address in the range
[r, n]
. A compliant solution that is both efficient and fully portable is currently unknown.
#ccccff
cpp
#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) {
if (cur == testPtr) {
return true;
}
}
return false;
}
void f() {
double foo[10];
double *x = &foo[0];
double bar;
std::cout << std::boolalpha << in_range(&bar, x, 10);
} | ## 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 Pointers
DF2668, DF2761, DF2762, DF2763, DF2766, DF2767, DF2768
LDRA tool suite
70 S, 87 S, 437 S, 438 S
Enhanced Enforcement
Parasoft C/C++test
CERT_CPP-CTR54-a
CERT_CPP-CTR54-b
CERT_CPP-CTR54-c
Do not compare iterators from different containers
Do not compare two unrelated pointers
Do not subtract two pointers that do not address elements of the same array
CERT C++: CTR54-CPP
Checks for subtraction or comparison between iterators from different containers (rule partially covered).
Related Vulnerabilities
Search for
vulnerabilities
resulting from the violation of this rule on the
CERT website
. | 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], paragraph 5 [
ISO/IEC 14882-2014
], in part, states the following:
If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.
Because iterators are a generalization of pointers, the same constraints apply to additive operators with random access iterators. Specifically, the C++ Standard, [iterator.requirements.general], paragraph 5, states the following:
Just as a regular pointer to an array guarantees that there is a pointer value pointing past the last element of the array, so for any iterator type there is an iterator value that points past the last element of a corresponding sequence. These values are called
past-the-end
values. Values of an iterator
i
for which the expression
*i
is defined are called
dereferenceable
. The library never assumes that past-the-end values are dereferenceable.
Do not allow an expression of integral type to add to or subtract from a pointer or random access iterator when the resulting value would overflow the bounds of the container. | #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 expression, but the resulting value could be outside the bounds of the container rather than a past-the-end value.
#ffcccc
cpp
#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;
}
} | #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 intention was to process up to 20 items in the container. Instead of assuming all containers will have 20 or more elements, the size of the container is used to determine the upper bound on the addition.
#ccccff
cpp
#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) {
// ...
}
} | ## 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. Iterators and standard template library containers exhibit the same behavior and caveats as pointers and arrays.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
CTR55-CPP
High
Likely
No
No
P9
L2 | 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 particular, a pointer to a base class cannot be used for pointer arithmetic when the array contains objects of a derived class type. —
end note
]
Pointer arithmetic does not account for polymorphic object sizes, and attempting to perform pointer arithmetic on a polymorphic object value results in
undefined behavior
.
The C++ Standard, [expr.sub], paragraph 1 [
ISO/IEC 14882-2014
], defines array subscripting as being identical to pointer arithmetic. Specifically, it states the following:
The expression
E1[E2]
is identical (by definition) to
*((E1)+(E2))
.
Do not use pointer arithmetic, including array subscripting, on polymorphic objects.
The following code examples assume the following static variables and class definitions.
cpp
int globI;
double globD;
struct S {
int i;
S() : i(globI++) {}
};
struct T : S {
double d;
T() : S(), d(globD++) {}
}; | #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 S, T, globI, globD ...
void f(const S *someSes, std::size_t count) {
for (std::size_t i = 0; i < count; ++i) {
std::cout << someSes[i].i << std::endl;
}
}
int main() {
T test[5];
f(test, 5);
}
## Noncompliant Code Example (Pointer Arithmetic)
In this noncompliant code example,
f()
accepts an array of
S
objects as its first parameter. However,
main()
passes an array of
T
objects as the first argument to
f()
, which results in
undefined behavior
due to the pointer arithmetic used within the
for
loop.
#FFCCCC
cpp
#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);
}
## Noncompliant Code Example (Array Subscripting)
In this noncompliant code example, the
for
loop uses array subscripting. Since array subscripts are computed using pointer arithmetic, this code also results in undefined behavior
.
#FFCCCC
cpp
#include <iostream>
// ... definitions for S, T, globI, globD ...
void f(const S *someSes, std::size_t count) {
for (std::size_t i = 0; i < count; ++i) {
std::cout << someSes[i].i << std::endl;
}
}
int main() {
T test[5];
f(test, 5);
} | #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(test, 5);
for (auto v : test) {
delete v;
}
}
#include <iostream>
#include <vector>
// ... definitions for S, T, globI, globD ...
template <typename Iter>
void f(Iter i, Iter e) {
for (; i != e; ++i) {
std::cout << (*i)->i << std::endl;
}
}
int main() {
std::vector<S *> test{new T, new T, new T, new T, new T};
f(test.cbegin(), test.cend());
for (auto v : test) {
delete v;
}
}
## Compliant Solution (Array)
Instead of having an array of objects, an array of pointers solves the problem of the objects being of different sizes, as in this compliant solution.
#ccccff
cpp
#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(test, 5);
for (auto v : test) {
delete v;
}
}
The elements in the arrays are no longer polymorphic objects (instead, they are pointers to polymorphic objects), and so there is no
undefined behavior
with the pointer arithmetic.
## Compliant Solution (std::vector)
Another approach is to use a standard template library (STL) container instead of an array and have
f()
accept iterators as parameters, as in this compliant solution. However, because STL containers require homogeneous elements, pointers are still required within the container.
#ccccff
cpp
#include <iostream>
#include <vector>
// ... definitions for S, T, globI, globD ...
template <typename Iter>
void f(Iter i, Iter e) {
for (; i != e; ++i) {
std::cout << (*i)->i << std::endl;
}
}
int main() {
std::vector<S *> test{new T, new T, new T, new T, new T};
f(test.cbegin(), test.cend());
for (auto v : test) {
delete v;
}
} | ## 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
(transitivity)
Providing an invalid ordering predicate for an associative container (e.g., sets, maps, multisets, and multimaps), or as a comparison criterion with the sorting algorithms, can result in erratic behavior or infinite loops [
Meyers 01
]. When an ordering predicate is required for an associative container or a generic standard template library algorithm, the predicate must meet the requirements for inducing a strict weak ordering. | #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 j) : i(i), j(j) {}
friend bool operator<(const S &lhs, const S &rhs) {
return lhs.i < rhs.i && lhs.j < rhs.j;
}
friend std::ostream &operator<<(std::ostream &os, const S& o) {
os << "i: " << o.i << ", j: " << o.j;
return os;
}
};
void f() {
std::set<S> t{S(1, 1), S(1, 2), S(2, 1)};
for (auto v : t) {
std::cout << v << std::endl;
}
}
## Noncompliant Code Example
In this noncompliant code example, the
std::set
object is created with a comparator that does not adhere to the strict weak ordering requirement. Specifically, it fails to return false for equivalent values. As a result, the behavior of iterating over the results from
std::set::equal_range
results in
unspecified behavior
.
#FFcccc
cpp
#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;
}
}
## Noncompliant Code Example
In this noncompliant code example, the objects stored in the std::set have an overloaded operator< implementation, allowing the objects to be compared with std::less. However, the comparison operation does not provide a strict weak ordering. Specifically, two sets, x and y, whose i values are both 1, but have differing j values can result in a situation where comp(x, y) and comp(y, x) are both false, failing the asymmetry requirements.
#FFcccc
cpp
#include <iostream>
#include <set>
class S {
int i, j;
public:
S(int i, int j) : i(i), j(j) {}
friend bool operator<(const S &lhs, const S &rhs) {
return lhs.i < rhs.i && lhs.j < rhs.j;
}
friend std::ostream &operator<<(std::ostream &os, const S& o) {
os << "i: " << o.i << ", j: " << o.j;
return os;
}
};
void f() {
std::set<S> t{S(1, 1), S(1, 2), S(2, 1)};
for (auto v : t) {
std::cout << v << std::endl;
}
} | #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) {}
friend bool operator<(const S &lhs, const S &rhs) {
return std::tie(lhs.i, lhs.j) < std::tie(rhs.i, rhs.j);
}
friend std::ostream &operator<<(std::ostream &os, const S& o) {
os << "i: " << o.i << ", j: " << o.j;
return os;
}
};
void f() {
std::set<S> t{S(1, 1), S(1, 2), S(2, 1)};
for (auto v : t) {
std::cout << v << std::endl;
}
}
## Compliant Solution
## This compliant solution uses the default comparator withstd::setinstead of providing an invalid one.
#ccccff
cpp
#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;
}
}
## Compliant Solution
## This compliant solution uses std::tie() to properly implement the strict weak ordering operator< predicate.
#ccccff
cpp
#include <iostream>
#include <set>
#include <tuple>
class S {
int i, j;
public:
S(int i, int j) : i(i), j(j) {}
friend bool operator<(const S &lhs, const S &rhs) {
return std::tie(lhs.i, lhs.j) < std::tie(rhs.i, rhs.j);
}
friend std::ostream &operator<<(std::ostream &os, const S& o) {
os << "i: " << o.i << ", j: " << o.j;
return os;
}
};
void f() {
std::set<S> t{S(1, 1), S(1, 2), S(2, 1)};
for (auto v : t) {
std::cout << v << std::endl;
}
} | ## 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 library implements numerous common algorithms that accept a predicate function object. The C++ Standard, [algorithms.general], paragraph 10
[
ISO/IEC 14882-2014
]
, states the following:
[
Note:
Unless otherwise specified, algorithms that take function objects as arguments are permitted to copy those function objects freely. Programmers for whom object identity is important should consider using a wrapper class that points to a noncopied implementation object such as
reference_wrapper<T>
, or some equivalent solution. —
end note
]
Because it is
implementation-defined
whether an algorithm copies a predicate function object, any such object must either
implement a function call operator that does not mutate state related to the function object's identity, such as nonstatic data members or captured values, or
wrap the predicate function object in a
std::reference_wrapper<T>
(or an equivalent solution).
Marking the function call operator as
const
is beneficial, but insufficient, because data members with the
mutable
storage class specifier may still be modified within a
const
member function. | #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;
}
};
template <typename Iter>
void print_container(Iter b, Iter e) {
std::cout << "Contains: ";
std::copy(b, e, std::ostream_iterator<decltype(*b)>(std::cout, " "));
std::cout << std::endl;
}
void f() {
std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_container(v.begin(), v.end());
v.erase(std::remove_if(v.begin(), v.end(), MutablePredicate()), v.end());
print_container(v.begin(), v.end());
}
Contains: 0 1 2 3 4 5 6 7 8 9
Contains: 0 1 3 4 6 7 8 9
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template <typename Iter>
void print_container(Iter b, Iter e) {
std::cout << "Contains: ";
std::copy(b, e, std::ostream_iterator<decltype(*b)>(std::cout, " "));
std::cout << std::endl;
}
void f() {
std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_container(v.begin(), v.end());
int timesCalled = 0;
v.erase(std::remove_if(v.begin(), v.end(), [timesCalled](const int &) mutable { return ++timesCalled == 3; }), v.end());
print_container(v.begin(), v.end());
}
## Noncompliant Code Example (Functor)
This noncompliant code example attempts to remove the third item in a container using a predicate that returns
true
only on its third invocation.
#ffcccc
cpp
#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;
}
};
template <typename Iter>
void print_container(Iter b, Iter e) {
std::cout << "Contains: ";
std::copy(b, e, std::ostream_iterator<decltype(*b)>(std::cout, " "));
std::cout << std::endl;
}
void f() {
std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_container(v.begin(), v.end());
v.erase(std::remove_if(v.begin(), v.end(), MutablePredicate()), v.end());
print_container(v.begin(), v.end());
}
However,
std::remove_if()
is permitted to construct and use extra copies of its predicate function. Any such extra copies may result in unexpected output.
Implementation Details
This program produces the following results using
gcc
4.8.1 with
libstdc++
.
cpp
Contains: 0 1 2 3 4 5 6 7 8 9
Contains: 0 1 3 4 6 7 8 9
This result arises because
std::remove_if
makes two copies of the predicate before invoking it. The first copy is used to determine the location of the first element in the sequence for which the predicate returns
true
. The subsequent copy is used for removing other elements in the sequence. This results in the third element (
2
) and sixth element (
5
) being removed; two distinct predicate functions are used.
## Noncompliant Code Example (Lambda)
Similar to the functor noncompliant code example, this noncompliant code example attempts to remove the third item in a container using a predicate lambda function that returns
true
only on its third invocation. As with the functor, this lambda carries local state information, which it attempts to mutate within its function call operator.
#ffcccc
cpp
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template <typename Iter>
void print_container(Iter b, Iter e) {
std::cout << "Contains: ";
std::copy(b, e, std::ostream_iterator<decltype(*b)>(std::cout, " "));
std::cout << std::endl;
}
void f() {
std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_container(v.begin(), v.end());
int timesCalled = 0;
v.erase(std::remove_if(v.begin(), v.end(), [timesCalled](const int &) mutable { return ++timesCalled == 3; }), v.end());
print_container(v.begin(), v.end());
} | #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;
}
};
template <typename Iter>
void print_container(Iter b, Iter e) {
std::cout << "Contains: ";
std::copy(b, e, std::ostream_iterator<decltype(*b)>(std::cout, " "));
std::cout << std::endl;
}
void f() {
std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_container(v.begin(), v.end());
MutablePredicate mp;
v.erase(std::remove_if(v.begin(), v.end(), std::ref(mp)), v.end());
print_container(v.begin(), v.end());
}
Contains: 0 1 2 3 4 5 6 7 8 9
Contains: 0 1 3 4 5 6 7 8 9
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template <typename Iter>
void print_container(Iter B, Iter E) {
std::cout << "Contains: ";
std::copy(B, E, std::ostream_iterator<decltype(*B)>(std::cout, " "));
std::cout << std::endl;
}
void f() {
std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_container(v.begin(), v.end());
v.erase(v.begin() + 3);
print_container(v.begin(), v.end());
}
## Compliant Solution (std::reference_wrapper)
This compliant solution uses
std::ref
to wrap the predicate in a
std::reference_wrapper<T>
object, ensuring that copies of the wrapper object all refer to the same underlying predicate object.
#ccccff
cpp
#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;
}
};
template <typename Iter>
void print_container(Iter b, Iter e) {
std::cout << "Contains: ";
std::copy(b, e, std::ostream_iterator<decltype(*b)>(std::cout, " "));
std::cout << std::endl;
}
void f() {
std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_container(v.begin(), v.end());
MutablePredicate mp;
v.erase(std::remove_if(v.begin(), v.end(), std::ref(mp)), v.end());
print_container(v.begin(), v.end());
}
The above com
pliant solution demonstrates using a reference wrapper over a functor object but can similarly be used with a stateful lambda.
The code produces the expected results, where only the third element is removed.
cpp
Contains: 0 1 2 3 4 5 6 7 8 9
Contains: 0 1 3 4 5 6 7 8 9
## Compliant Solution (Iterator Arithmetic)
Removing a specific element of a container does not require a predicate function but can instead simply use
std::vector::erase()
, as in this compliant solution.
#ccccff
cpp
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
template <typename Iter>
void print_container(Iter B, Iter E) {
std::cout << "Contains: ";
std::copy(B, E, std::ostream_iterator<decltype(*B)>(std::cout, " "));
std::cout << std::endl;
}
void f() {
std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
print_container(v.begin(), v.end());
v.erase(v.begin() + 3);
print_container(v.begin(), v.end());
} | ## 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: function parameter packs and use of a C-style ellipsis as the final parameter declaration.
Variadic functions are flexible because they accept a varying number of arguments of differing types. However, they can also be hazardous. A variadic function using a C-style ellipsis (hereafter called a
C-style variadic function
) has no mechanisms to check the type safety of arguments being passed to the function or to check that the number of arguments being passed matches the semantics of the function definition. Consequently, a runtime call to a C-style variadic function that passes inappropriate arguments yields undefined behavior. Such
undefined behavior
could be
exploited
to run arbitrary code.
Do not define C-style variadic functions. (The declaration of a C-style variadic function that is never defined is permitted, as it is not harmful and can be useful in unevaluated contexts.)
Issues with C-style variadic functions can be avoided by using variadic functions defined with function parameter packs for situations in which a variable number of arguments should be passed to a function. Additionally, function currying can be used as a replacement to variadic functions. For example, in contrast to C's
printf()
family of functions, C++ output is implemented with the overloaded single-argument
std::cout::operator<<()
operators. | #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 integers together. The function reads arguments until the value
0
is found. Calling this function without passing the value
0
as an argument (after the first two arguments) results in undefined behavior. Furthermore, passing any type other than an
int
also results in undefined behavior.
#FFCCCC
cpp
#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;
} | #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 + add(rest...);
}
#include <type_traits>
template <typename Arg, typename... Ts, typename std::enable_if<std::is_integral<Arg>::value>::type * = nullptr>
int add(Arg i, Arg j, Ts... all) {
int values[] = { j, all... };
int r = i;
for (auto v : values) {
r += v;
}
return r;
}
## Compliant Solution (Recursive Pack Expansion)
In this compliant solution, a variadic function using a function parameter pack is used to implement the
add()
function, allowing identical behavior for call sites. Unlike the C-style variadic function used in the noncompliant code example, this compliant solution does not result in undefined behavior if the list of parameters is not terminated with
0
. Additionally, if any of the values passed to the function are not integers, the code is
ill-formed
rather than producing undefined behavior.
#ccccff
cpp
#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 + add(rest...);
}
This compliant solution makes use of
std::enable_if
to ensure that any nonintegral argument value results in an ill-formed program.
## Compliant Solution (Braced Initializer List Expansion)
An alternative compliant solution that does not require recursive expansion of the function parameter pack instead expands the function parameter pack into a list of values as part of a braced initializer list. Since narrowing conversions are not allowed in a braced initializer list, the type safety is preserved despite the
std::enable_if
not involving any of the variadic arguments.
#ccccff
cpp
#include <type_traits>
template <typename Arg, typename... Ts, typename std::enable_if<std::is_integral<Arg>::value>::type * = nullptr>
int add(Arg i, Arg j, Ts... all) {
int values[] = { j, all... };
int r = i;
for (auto v : values) {
r += v;
}
return r;
} | ## 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 library header shall not
#define
or
#undef
names declared in any standard library header.
A translation unit shall not
#define
or
#undef
names lexically identical to keywords, to the identifiers listed in Table 3, or to the
attribute-token
s described in 7.6.
Each name that contains a double underscore
__
or begins with an underscore followed by an uppercase letter is reserved to the implementation for any use.
Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
Each name declared as an object with external linkage in a header is reserved to the implementation to designate that library object with external linkage, both in namespace
std
and in the global namespace.
Each global function signature declared with external linkage in a header is reserved to the implementation to designate that function signature with external linkage.
Each name from the Standard C library declared with external linkage is reserved to the implementation for use as a name with
extern "C"
linkage, both in namespace
std
and in the global namespace.
Each function signature from the Standard C library declared with external linkage is reserved to the implementation for use as a function signature with both
extern "C"
and
extern "C++"
linkage, or as a name of namespace scope in the global namespace.
For each type
T
from the Standard C library, the types
::T
and
std::T
are reserved to the implementation and, when defined,
::T
shall be identical to
std::T
.
Literal suffix identifiers that do not start with an underscore are reserved for future standardization.
The identifiers and attribute names referred to in the preceding excerpt are
override
,
final
,
alignas
,
carries_dependency
,
deprecated
, and
noreturn
.
No other identifiers are reserved. Declaring or defining an identifier in a context in which it is reserved results in
undefined behavior
. Do not declare or define a reserved identifier. | #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 int count) {
return count < _limit ? count : _limit;
}
#include <cinttypes> // for int_fast16_t
void f(std::int_fast16_t val) {
enum { MAX_SIZE = 80 };
// ...
}
## Noncompliant Code Example (Header Guard)
A common practice is to use a macro in a preprocessor conditional that guards against multiple inclusions of a header file. While this is a recommended practice, many programs use reserved names as the header guards. Such a name may clash with reserved names defined by the implementation of the C++ standard template library in its headers or with reserved names implicitly predefined by the compiler even when no C++ standard library header is included.
#FFCCCC
cpp
#ifndef _MY_HEADER_H_
#define _MY_HEADER_H_
// Contents of <my_header.h>
#endif // _MY_HEADER_H_
## Noncompliant Code Example (User-Defined Literal)
In this noncompliant code example, a user-defined literal
operator"" x
is declared. However, literal suffix identifiers are required to start with an underscore; literal suffixes without the underscore prefix are reserved for future library implementations.
#FFCCCC
cpp
#include <cstddef>
unsigned int operator"" x(const char *, std::size_t);
## Noncompliant Code Example (File Scope Objects)
In this noncompliant code example, the names of the file scope objects
_max_limit
and
_limit
both begin with an underscore. Because it is
static
, the declaration of
_max_limit
might seem to be impervious to clashes with names defined by the implementation. However, because the header
<cstddef>
is included to define
std::size_t
, a potential for a name clash exists. (Note, however, that a conforming compiler may implicitly declare reserved names regardless of whether any C++ standard template library header has been explicitly included.) In addition, because
_limit
has external linkage, it may clash with a symbol with the same name defined in the language runtime library even if such a symbol is not declared in any header. Consequently, it is unsafe to start the name of any file scope identifier with an underscore even if its linkage limits its visibility to a single translation unit.
#FFCCCC
cpp
#include <cstddef> // std::for size_t
static const std::size_t _max_limit = 1024;
std::size_t _limit = 100;
unsigned int get_value(unsigned int count) {
return count < _limit ? count : _limit;
}
## Noncompliant Code Example (Reserved Macros)
In this noncompliant code example, because the C++ standard template library header
<cinttypes>
is specified to include
<cstdint>
, as per [c.files] paragraph 4
[
ISO/IEC 14882-2014
]
, the name
MAX_SIZE
conflicts with the name of the
<cstdint>
header macro used to denote the upper limit of
std:size_t.
#ffcccc
cpp
#include <cinttypes> // for int_fast16_t
void f(std::int_fast16_t val) {
enum { MAX_SIZE = 80 };
// ...
} | #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) {
return count < limit ? count : limit;
}
#include <cinttypes> // for std::int_fast16_t
void f(std::int_fast16_t val) {
enum { BufferSize = 80 };
// ...
}
## Compliant Solution (Header Guard)
## This compliant solution avoids using leading or trailing underscores in the name of the header guard.
#ccccff
cpp
#ifndef MY_HEADER_H
#define MY_HEADER_H
// Contents of <my_header.h>
#endif // MY_HEADER_H
## Compliant Solution (User-Defined Literal)
## In this compliant solution, the user-defined literal is namedoperator"" _x, which is not a reserved identifier.
#ccccff
cpp
#include <cstddef>
unsigned int operator"" _x(const char *, std::size_t);
The name of the user-defined literal is
operator"" _x
and not
_x
, which would have otherwise been reserved for the global namespace.
## Compliant Solution (File Scope Objects)
## In this compliant solution, file scope identifiers do not begin with an underscore.
#ccccff
cpp
#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) {
return count < limit ? count : limit;
}
## Compliant Solution (Reserved Macros)
## This compliant solution avoids redefining reserved names.
#ccccff
cpp
#include <cinttypes> // for std::int_fast16_t
void f(std::int_fast16_t val) {
enum { BufferSize = 80 };
// ...
} | ## 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-defined-literals
The
-Wreserved-id-macro
flag is not enabled by default or with
-Wall
, but is enabled with
-Weverything
. This flag does not
catch all instances of this rule, such as redefining reserved names.
LANG.ID.NU.MK
LANG.STRUCT.DECL.RESERVED
Macro name is C keyword
Declaration of reserved name
C++5003
MISRA.DEFINE.WRONGNAME
MISRA.DEFINE.WRONGNAME.UNDERSCORE
MISRA.UNDEF.WRONGNAME
MISRA.UNDEF.WRONGNAME.UNDERSCORE
MISRA.STDLIB.WRONGNAME
MISRA.STDLIB.WRONGNAME.UNDERSCORE
LDRA tool suite
86 S, 218 S, 219 S, 580 S
Fully implemented
Parasoft C/C++test
CERT_CPP-DCL51-a
CERT_CPP-DCL51-b
CERT_CPP-DCL51-c
CERT_CPP-DCL51-d
CERT_CPP-DCL51-e
CERT_CPP-DCL51-f
Do not #define or #undef identifiers with names which start with underscore
Do not redefine reserved words
Do not #define nor #undef identifier 'defined'
The names of standard library macros, objects and functions shall not be reused
The names of standard library macros, objects and functions shall not be reused (C90)
The names of standard library macros, objects and functions shall not be reused (C99)
Polyspace Bug Finder
CERT C++: DCL51-CPP
Checks for redefinitions of reserved identifiers (rule partially covered)
PVS-Studio
V1059
reserved-identifier
Partially checked
978
Related Vulnerabilities
Search for
vulnerabilities
resulting from the violation of this rule on the
CERT website
. | 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
typedef-name
(7.1.3, 14.1) or
decltype-specifier
(7.1.6.2), in which case the cv-qualifiers are ignored.
Thus, C++ prohibits or ignores the
cv-qualification
of a reference type. Only a value of non-reference type may be cv-qualified.
When attempting to
const
-qualify a type as part of a declaration that uses reference type, a programmer may accidentally write
#ffcccc
cpp
char &const p;
instead of
#ccccff
cpp
char const &p; // Or: const char &p;
Do not attempt to cv-qualify a reference type because it results in
undefined behavior
. A
conforming
compiler is required to issue a
diagnostic message
. However, if the compiler does not emit a
fatal diagnostic
, the program may produce surprising results, such as allowing the character referenced by
p
to be mutated. | #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: read-only variable is not assignable
std::cout << c << std::endl;
}
## Noncompliant Code Example
In this noncompliant code example, a
const
-qualified reference to a
char
is formed instead of a reference to a
const
-qualified
char.
This results in undefined behavior.
#ffcccc
cpp
#include <iostream>
void f(char c) {
char &const p = c;
p = 'p';
std::cout << c << std::endl;
}
Implementation Details (MSVC)
With
Microsoft Visual Studio
2015, this code compiles successfully with a warning diagnostic.
warning C4227: anachronism used : qualifiers on reference are ignored
When run, the code outputs the following.
p
Implementation Details (Clang)
With
Clang
3.9, this code produces a fatal diagnostic.
error: 'const' qualifier may not be applied to a reference
## Noncompliant Code Example
This noncompliant code example correctly declares
p
to be a reference to a const-qualified
char
. The subsequent modification of
p
makes the program
ill-formed
.
#ffcccc
cpp
#include <iostream>
void f(char c) {
const char &p = c;
p = 'p'; // Error: read-only variable is not assignable
std::cout << c << std::endl;
} | #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 Detection
Tool
Version
Checker
Description
CertC++-DCL52
C++0014
Klocwork
CERT.DCL.REF_TYPE.CONST_OR_VOLATILE
Parasoft C/C++test
CERT_CPP-DCL52-a
Never qualify a reference type with 'const' or 'volatile'
Polyspace Bug Finder
CERT C++: DCL52-CPP
Checks for:
const-qualified reference types
Modification of const-qualified reference types
Rule fully covered.
Clang checks for violations of this rule and produces an error without the need to specify any special flags or options
.
S3708
Related Vulnerabilities
Search for
vulnerabilities
resulting from the violation of this rule on the
CERT website
. | 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
], in part, states the following:
There is an ambiguity in the grammar involving
expression-statement
s and declarations: An
expression-statement
with a function-style explicit type conversion as its leftmost subexpression can be indistinguishable from a declaration where the first declarator starts with a
(
. In those cases the statement is a declaration. [Note: To disambiguate, the whole statement might have to be examined to determine if it is an
expression-statement
or a declaration. ...
A similarly vexing parse exists within the context of a declaration where syntax can be ambiguously interpreted as either a function declaration or a declaration with a function-style cast as the initializer. The C++ Standard, [dcl.ambig.res], paragraph 1, in part, states the following:
The ambiguity arising from the similarity between a function-style cast and a declaration mentioned in 6.8 can also occur in the context of a declaration. In that context, the choice is between a function declaration with a redundant set of parentheses around a parameter name and an object declaration with a function-style cast as the initializer. Just as for the ambiguities mentioned in 6.8, the resolution is to consider any construct that could possibly be a declaration a declaration.
Do not write a syntactically ambiguous declaration. With the advent of uniform initialization syntax using a braced-init-list, there is now syntax that unambiguously specifies a declaration instead of an expression statement. Declarations can also be disambiguated by using nonfunction-style casts, by initializing using =, or by removing extraneous parenthesis around the parameter name. | #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 {
explicit Widget(int i) { std::cout << "Widget constructed" << std::endl; }
};
struct Gadget {
explicit Gadget(Widget wid) { std::cout << "Gadget constructed" << std::endl; }
};
void f() {
int i = 3;
Gadget g(Widget(i));
std::cout << i << std::endl;
}
Gadget g(Widget i);
## Noncompliant Code Example
In this noncompliant code example, an anonymous local variable of type
std::unique_lock
is expected to lock and unlock the mutex
m
by virtue of
RAII.
However, the declaration is syntactically ambiguous as it can be interpreted as declaring an anonymous object and calling its single-argument converting constructor or interpreted as declaring an object named
m
and default constructing it. The syntax used in this example defines the latter instead of the former, and so the mutex object is never locked.
#FFCCCC
cpp
#include <mutex>
static std::mutex m;
static int shared_resource;
void increment_by_42() {
std::unique_lock<std::mutex>(m);
shared_resource += 42;
}
## Noncompliant Code Example
In this noncompliant code example, an attempt is made to declare a local variable,
w
, of type
Widget
while executing the default constructor. However, this declaration is syntactically ambiguous where the code could be either a declaration of a function pointer accepting no arguments and returning a
Widget
or a declaration of a local variable of type
Widget
. The syntax used in this example defines the former instead of the latter.
#FFCCCC
cpp
#include <iostream>
struct Widget {
Widget() { std::cout << "Constructed" << std::endl; }
};
void f() {
Widget w();
}
As a result, this program compiles and prints no output because the default constructor is never actually invoked.
## Noncompliant Code Example
This noncompliant code example demonstrates a vexing parse. The declaration
Gadget g(Widget(i));
is not parsed as declaring a
Gadget
object with a single argument. It is instead parsed as a function declaration with a redundant set of parentheses around a parameter.
#FFCCCC
cpp
#include <iostream>
struct Widget {
explicit Widget(int i) { std::cout << "Widget constructed" << std::endl; }
};
struct Gadget {
explicit Gadget(Widget wid) { std::cout << "Gadget constructed" << std::endl; }
};
void f() {
int i = 3;
Gadget g(Widget(i));
std::cout << i << std::endl;
}
Parentheses around parameter names are optional, so the following is a semantically identical spelling of the declaration.
#ccccff
cpp
Gadget g(Widget i);
As a result, this program is well-formed and prints only
3
as output because no
Gadget
or
Widget
objects are constructed. | #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{}; // Use direct initialization
}
#include <iostream>
struct Widget {
explicit Widget(int i) { std::cout << "Widget constructed" << std::endl; }
};
struct Gadget {
explicit Gadget(Widget wid) { std::cout << "Gadget constructed" << std::endl; }
};
void f() {
int i = 3;
Gadget g1((Widget(i))); // Use extra parentheses
Gadget g2{Widget(i)}; // Use direct initialization
std::cout << i << std::endl;
}
Widget constructed
Gadget constructed
Widget constructed
Gadget constructed
3
## Compliant Solution
In this compliant solution, the lock object is given an identifier (other than
m
) and the proper converting constructor is called.
#ccccff
cpp
#include <mutex>
static std::mutex m;
static int shared_resource;
void increment_by_42() {
std::unique_lock<std::mutex> lock(m);
shared_resource += 42;
}
## Compliant Solution
This compliant solution shows two equally compliant ways to write the declaration. The first way is to elide the parentheses after the variable declaration, which ensures the syntax is that of a variable declaration instead of a function declaration. The second way is to use a
braced-init-list
to direct-initialize the local variable.
#ccccff
cpp
#include <iostream>
struct Widget {
Widget() { std::cout << "Constructed" << std::endl; }
};
void f() {
Widget w1; // Elide the parentheses
Widget w2{}; // Use direct initialization
}
Running this program produces the output
Constructed
twice, once for
w1
and once for
w2
.
## Compliant Solution
This compliant solution demonstrates two equally compliant ways to write the declaration of
g
. The first declaration,
g1
, uses an extra set of parentheses around the argument to the constructor call, forcing the compiler to parse it as a local variable declaration of type
Gadget
instead of as a function declaration. The second declaration,
g2
, uses direct initialization to similar effect.
#ccccff
cpp
#include <iostream>
struct Widget {
explicit Widget(int i) { std::cout << "Widget constructed" << std::endl; }
};
struct Gadget {
explicit Gadget(Widget wid) { std::cout << "Gadget constructed" << std::endl; }
};
void f() {
int i = 3;
Gadget g1((Widget(i))); // Use extra parentheses
Gadget g2{Widget(i)}; // Use direct initialization
std::cout << i << std::endl;
}
Running this program produces the expected output.
cpp
Widget constructed
Gadget constructed
Widget constructed
Gadget constructed
3 | ## 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
Checker
Description
LANG.STRUCT.DECL.FNEST
Nested Function Declaration
C++1109, C++2510
Klocwork
CERT.DCL.AMBIGUOUS_DECL
LDRA tool suite
296 S
Partially implemented
Parasoft C/C++test
CERT_CPP-DCL53-a
CERT_CPP-DCL53-b
CERT_CPP-DCL53-c
Parameter names in function declarations should not be enclosed in parentheses
Local variable names in variable declarations should not be enclosed in parentheses
Avoid function declarations that are syntactically ambiguous
Polyspace Bug Finder
CERT C++: DCL53-CPP
Checks for declarations that can be confused between:
Function and object declaration
Unnamed object or function parameter declaration
Rule fully covered.
-Wvexing-parse
S3468
Related Vulnerabilities
Search for other
vulnerabilities
resulting from the violation of this rule on the
CERT website
. | 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 to violate rules such as
. For instance, if an overloaded allocation function uses a private heap to perform its allocations, passing a pointer returned by it to the default deallocation function will likely cause
undefined behavior
. Even in situations in which the allocation function ultimately uses the default allocator to obtain a pointer to memory, failing to overload a corresponding deallocation function may leave the program in an unexpected state by not updating internal data for the custom allocator.
It is acceptable to define a deleted allocation or deallocation function without its corresponding
free store
function. For instance, it is a common practice to define a deleted non-placement allocation or deallocation function as a class member function when the class also defines a placement
new
function. This prevents accidental allocation via calls to
new
for that class type or deallocation via calls to
delete
on pointers to an object of that class type. It is acceptable to declare, but not define, a private allocation or deallocation function without its corresponding free store function for similar reasons. However, a definition must not be provided as that still allows access to the free store function within a class member function. | #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>
extern "C++" void update_bookkeeping(void *allocated_ptr, std::size_t size, bool alloc);
struct S {
void *operator new(std::size_t size) noexcept(false) {
void *ptr = ::operator new(size);
update_bookkeeping(ptr, size, true);
return ptr;
}
};
## Noncompliant Code Example
In this noncompliant code example, an allocation function is overloaded at global scope. However, the corresponding deallocation function is not declared. Were an object to be allocated with the overloaded allocation function, any attempt to delete the object would result in
undefined behavior
in violation of
.
#FFcccc
cpp
#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.
## Noncompliant Code Example
In this noncompliant code example,
operator new()
is overloaded at class scope, but
operator delete()
is not similarly overloaded at class scope. Despite that the overloaded allocation function calls through to the default global allocation function, were an object of type
S
to be allocated, any attempt to delete the object would result in leaving the program in an indeterminate state due to failing to update allocation bookkeeping accordingly.
#FFcccc
cpp
#include <new>
extern "C++" void update_bookkeeping(void *allocated_ptr, std::size_t size, bool alloc);
struct S {
void *operator new(std::size_t size) noexcept(false) {
void *ptr = ::operator new(size);
update_bookkeeping(ptr, size, true);
return ptr;
}
}; | #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);
}
throw std::bad_alloc();
}
static void dealloc(void *ptr) noexcept {
if (h) {
(void)::HeapFree(h, 0, ptr);
}
}
};
HANDLE HeapAllocator::h = nullptr;
bool HeapAllocator::init = false;
void *operator new(std::size_t size) noexcept(false) {
return HeapAllocator::alloc(size);
}
void operator delete(void *ptr) noexcept {
return HeapAllocator::dealloc(ptr);
}
#include <new>
extern "C++" void update_bookkeeping(void *allocated_ptr, std::size_t size, bool alloc);
struct S {
void *operator new(std::size_t size) noexcept(false) {
void *ptr = ::operator new(size);
update_bookkeeping(ptr, size, true);
return ptr;
}
void operator delete(void *ptr, std::size_t size) noexcept {
::operator delete(ptr);
update_bookkeeping(ptr, size, false);
}
};
## Compliant Solution
## In this compliant solution, the corresponding deallocation function is also defined at global scope.
#ccccff
cpp
#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);
}
throw std::bad_alloc();
}
static void dealloc(void *ptr) noexcept {
if (h) {
(void)::HeapFree(h, 0, ptr);
}
}
};
HANDLE HeapAllocator::h = nullptr;
bool HeapAllocator::init = false;
void *operator new(std::size_t size) noexcept(false) {
return HeapAllocator::alloc(size);
}
void operator delete(void *ptr) noexcept {
return HeapAllocator::dealloc(ptr);
}
true
This code has a race condition. We should (1) fix the race condition, and (2) point to a rule about preventing race conditions (that we don't currently have!).
## Compliant Solution
## In this compliant solution, the correspondingoperator delete()is overloaded at the same class scope.
#ccccff
cpp
#include <new>
extern "C++" void update_bookkeeping(void *allocated_ptr, std::size_t size, bool alloc);
struct S {
void *operator new(std::size_t size) noexcept(false) {
void *ptr = ::operator new(size);
update_bookkeeping(ptr, size, true);
return ptr;
}
void operator delete(void *ptr, std::size_t size) noexcept {
::operator delete(ptr);
update_bookkeeping(ptr, size, false);
}
}; | ## 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++-DCL54
misc-new-delete-overloads
Checked with
clang-tidy
.
C++2160
Klocwork
CERT.DCL.SAME_SCOPE_ALLOC_DEALLOC
Parasoft C/C++test
CERT_CPP-DCL54-a
Always provide new and delete together
Polyspace Bug Finder
CERT C++: DCL54-CPP
Checks for mismatch between overloaded operator new and operator delete (rule fully covered)
new-delete-pairwise
Partially checked
S1265
Related Vulnerabilities
Search for
vulnerabilities
resulting from the violation of this rule on the
CERT website
. | 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. The order of allocation of non-static data members with different access control is unspecified. Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions and virtual base classes.
Further, [class.bit], paragraph 1, in part, states the following:
Allocation of bit-fields within a class object is implementation-defined. Alignment of bit-fields is implementation-defined. Bit-fields are packed into some addressable allocation unit.
Thus, padding bits may be present at any location within a class object instance (including at the beginning of the object, in the case of an unnamed bit-field as the first member declared in a class). Unless initialized by zero-initialization, padding bits contain
indeterminate values
that may contain sensitive information.
When passing a pointer to a class object instance across a
trust boundary
to a different trusted domain, the programmer must ensure that the padding bits of such an object do not contain sensitive information. | #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 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{};
arg.a = 1;
arg.b = 2;
arg.c = 3;
copy_to_user(usr_buf, &arg, sizeof(arg));
}
#include <cstddef>
class base {
public:
virtual ~base() = default;
};
class test : public virtual base {
alignas(32) double h;
char i;
unsigned j : 80;
protected:
unsigned k;
unsigned l : 4;
unsigned short m : 3;
public:
char n;
double o;
test(double h, char i, unsigned j, unsigned k, unsigned l, unsigned short m,
char n, double o) :
h(h), i(i), j(j), k(k), l(l), m(m), n(n), o(o) {}
virtual void foo();
};
// 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{0.0, 1, 2, 3, 4, 5, 6, 7.0};
copy_to_user(usr_buf, &arg, sizeof(arg));
}
## Noncompliant Code Example
This noncompliant code example runs in kernel space and copies data from
arg
to user space. However, padding bits may be used within the object, for example, to ensure the proper alignment of class data members. These padding bits may contain sensitive information that may then be leaked when the data is copied to user space, regardless of how the data is copied.
#FFcccc
cpp
#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));
}
## Noncompliant Code Example
In this noncompliant code example,
arg
is value-initialized through direct initialization. Because
test
does not have a user-provided default constructor, the value-initialization is preceded by a zero-initialization that guarantees the padding bits are initialized to
0
before any further initialization occurs. It is akin to using
std::memset()
to initialize all of the bits in the object to
0
.
#FFcccc
cpp
#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{};
arg.a = 1;
arg.b = 2;
arg.c = 3;
copy_to_user(usr_buf, &arg, sizeof(arg));
}
However, compilers are free to implement
arg.b = 2
by setting the low byte of a 32-bit register to
2
, leaving the high bytes unchanged, and storing all 32 bits of the register into memory. This could leak the high-order bytes resident in the register to a user.
## Noncompliant Code Example
## In this noncompliant code example, padding bits may abound, including
alignment padding bits after a virtual method table or virtual base class data to align a subsequent data member,
alignment padding bits to position a subsequent data member on a properly aligned boundary,
alignment padding bits to position data members of varying access control levels.
bit-field padding bits when the sequential set of bit-fields does not fill an entire allocation unit,
bit-field padding bits when two adjacent bit-fields are declared with different underlying types,
padding bits when a bit-field is declared with a length greater than the number of bits in the underlying allocation unit, or
padding bits to ensure a class instance will be appropriately aligned for use within an array.
This code example runs in kernel space and copies data from
arg
to user space. However, the padding bits within the object instance may contain sensitive information that will then be leaked when the data is copied to user space.
#FFcccc
cpp
#include <cstddef>
class base {
public:
virtual ~base() = default;
};
class test : public virtual base {
alignas(32) double h;
char i;
unsigned j : 80;
protected:
unsigned k;
unsigned l : 4;
unsigned short m : 3;
public:
char n;
double o;
test(double h, char i, unsigned j, unsigned k, unsigned l, unsigned short m,
char n, double o) :
h(h), i(i), j(j), k(k), l(l), m(m), n(n), o(o) {}
virtual void foo();
};
// 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{0.0, 1, 2, 3, 4, 5, 6, 7.0};
copy_to_user(usr_buf, &arg, sizeof(arg));
}
Padding bits are implementation-defined, so the layout of the class object may differ between compilers or architectures. When compiled with
GCC
5.3.0 for x86-32, the
test
object requires 96 bytes of storage to accommodate 29 bytes of data (33 bytes including the vtable) and has the following layout.
Offset (bytes (bits))
Storage Size (bytes (bits))
Reason
Offset
Storage Size
Reason
0
1 (32)
vtable pointer
56 (448)
4 (32)
unsigned k
4 (32)
28 (224)
data member alignment padding
60 (480)
0 (4)
unsigned l : 4
32 (256)
8 (64)
double h
60 (484)
0 (3)
unsigned short m : 3
40 (320)
1 (8)
char i
60 (487)
0 (1)
unused bit-field bits
41 (328)
3 (24)
data member
alignment padding
61 (488)
1 (8)
char n
44 (352)
4 (32)
unsigned j : 80
62 (496)
2 (16)
data member alignment padding
48 (384)
6 (48)
extended bit-field size padding
64 (512)
8 (64)
double o
54 (432)
2 (16)
alignment padding
72 (576)
24 (192)
class alignment padding | #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)];
std::size_t offset = 0;
std::memcpy(buf + offset, &arg.a, sizeof(arg.a));
offset += sizeof(arg.a);
std::memcpy(buf + offset, &arg.b, sizeof(arg.b));
offset += sizeof(arg.b);
std::memcpy(buf + offset, &arg.c, sizeof(arg.c));
offset += sizeof(arg.c);
copy_to_user(usr_buf, buf, offset /* size of info copied */);
}
#include <cstddef>
struct test {
int a;
char b;
char padding_1, padding_2, padding_3;
int c;
test(int a, char b, int c) : a(a), b(b),
padding_1(0), padding_2(0), padding_3(0),
c(c) {}
};
// Ensure c is the next byte after the last padding byte.
static_assert(offsetof(test, c) == offsetof(test, padding_3) + 1,
"Object contains intermediate padding");
// Ensure there is no trailing padding.
static_assert(sizeof(test) == offsetof(test, c) + sizeof(int),
"Object contains trailing padding");
// 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>
#include <cstring>
class base {
public:
virtual ~base() = default;
};
class test : public virtual base {
alignas(32) double h;
char i;
unsigned j : 80;
protected:
unsigned k;
unsigned l : 4;
unsigned short m : 3;
public:
char n;
double o;
test(double h, char i, unsigned j, unsigned k, unsigned l, unsigned short m,
char n, double o) :
h(h), i(i), j(j), k(k), l(l), m(m), n(n), o(o) {}
virtual void foo();
bool serialize(unsigned char *buffer, std::size_t &size) {
if (size < sizeof(test)) {
return false;
}
std::size_t offset = 0;
std::memcpy(buffer + offset, &h, sizeof(h));
offset += sizeof(h);
std::memcpy(buffer + offset, &i, sizeof(i));
offset += sizeof(i);
unsigned loc_j = j; // Only sizeof(unsigned) bits are valid, so this is not narrowing.
std::memcpy(buffer + offset, &loc_j, sizeof(loc_j));
offset += sizeof(loc_j);
std::memcpy(buffer + offset, &k, sizeof(k));
offset += sizeof(k);
unsigned char loc_l = l & 0b1111;
std::memcpy(buffer + offset, &loc_l, sizeof(loc_l));
offset += sizeof(loc_l);
unsigned short loc_m = m & 0b111;
std::memcpy(buffer + offset, &loc_m, sizeof(loc_m));
offset += sizeof(loc_m);
std::memcpy(buffer + offset, &n, sizeof(n));
offset += sizeof(n);
std::memcpy(buffer + offset, &o, sizeof(o));
offset += sizeof(o);
size -= offset;
return true;
}
};
// Safely copy bytes to user space.
extern int copy_to_user(void *dest, void *src, size_t size);
void do_stuff(void *usr_buf) {
test arg{0.0, 1, 2, 3, 4, 5, 6, 7.0};
// May be larger than strictly needed, will be updated by
// calling serialize() to the size of the buffer remaining.
std::size_t size = sizeof(arg);
unsigned char buf[sizeof(arg)];
if (arg.serialize(buf, size)) {
copy_to_user(usr_buf, buf, sizeof(test) - size);
} else {
// Handle error
}
}
## Compliant Solution
## This compliant solution serializes the structure data before copying it to an untrusted context.
#ccccff
cpp
#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)];
std::size_t offset = 0;
std::memcpy(buf + offset, &arg.a, sizeof(arg.a));
offset += sizeof(arg.a);
std::memcpy(buf + offset, &arg.b, sizeof(arg.b));
offset += sizeof(arg.b);
std::memcpy(buf + offset, &arg.c, sizeof(arg.c));
offset += sizeof(arg.c);
copy_to_user(usr_buf, buf, offset /* size of info copied */);
}
This code ensures that no uninitialized padding bits are copied to unprivileged users. The structure copied to user space is now a packed structure and the
copy_to_user()
function would need to unpack it to recreate the original, padded structure.
## Compliant Solution (Padding Bytes)
Padding bits can be explicitly declared as fields within the structure. This solution is not portable, however, because it depends on the implementation and target memory architecture. The following solution is specific to the x86-32 architecture.
#ccccff
cpp
#include <cstddef>
struct test {
int a;
char b;
char padding_1, padding_2, padding_3;
int c;
test(int a, char b, int c) : a(a), b(b),
padding_1(0), padding_2(0), padding_3(0),
c(c) {}
};
// Ensure c is the next byte after the last padding byte.
static_assert(offsetof(test, c) == offsetof(test, padding_3) + 1,
"Object contains intermediate padding");
// Ensure there is no trailing padding.
static_assert(sizeof(test) == offsetof(test, c) + sizeof(int),
"Object contains trailing padding");
// 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));
}
The
static_assert()
declaration accepts a constant expression and an
error message
. The expression is evaluated at compile time and, if false, the compilation is terminated and the error message is used as the diagnostic. The explicit insertion of the padding bytes into the
struct
should ensure that no additional padding bytes are added by the compiler, and consequently both static assertions should be true. However, it is necessary to validate these assumptions to ensure that the solution is correct for a particular implementation.
## Compliant Solution
Due to the complexity of the data structure, this compliant solution serializes the object data before copying it to an untrusted context instead of attempting to account for all of the padding bytes manually.
#ccccff
cpp
#include <cstddef>
#include <cstring>
class base {
public:
virtual ~base() = default;
};
class test : public virtual base {
alignas(32) double h;
char i;
unsigned j : 80;
protected:
unsigned k;
unsigned l : 4;
unsigned short m : 3;
public:
char n;
double o;
test(double h, char i, unsigned j, unsigned k, unsigned l, unsigned short m,
char n, double o) :
h(h), i(i), j(j), k(k), l(l), m(m), n(n), o(o) {}
virtual void foo();
bool serialize(unsigned char *buffer, std::size_t &size) {
if (size < sizeof(test)) {
return false;
}
std::size_t offset = 0;
std::memcpy(buffer + offset, &h, sizeof(h));
offset += sizeof(h);
std::memcpy(buffer + offset, &i, sizeof(i));
offset += sizeof(i);
unsigned loc_j = j; // Only sizeof(unsigned) bits are valid, so this is not narrowing.
std::memcpy(buffer + offset, &loc_j, sizeof(loc_j));
offset += sizeof(loc_j);
std::memcpy(buffer + offset, &k, sizeof(k));
offset += sizeof(k);
unsigned char loc_l = l & 0b1111;
std::memcpy(buffer + offset, &loc_l, sizeof(loc_l));
offset += sizeof(loc_l);
unsigned short loc_m = m & 0b111;
std::memcpy(buffer + offset, &loc_m, sizeof(loc_m));
offset += sizeof(loc_m);
std::memcpy(buffer + offset, &n, sizeof(n));
offset += sizeof(n);
std::memcpy(buffer + offset, &o, sizeof(o));
offset += sizeof(o);
size -= offset;
return true;
}
};
// Safely copy bytes to user space.
extern int copy_to_user(void *dest, void *src, size_t size);
void do_stuff(void *usr_buf) {
test arg{0.0, 1, 2, 3, 4, 5, 6, 7.0};
// May be larger than strictly needed, will be updated by
// calling serialize() to the size of the buffer remaining.
std::size_t size = sizeof(arg);
unsigned char buf[sizeof(arg)];
if (arg.serialize(buf, size)) {
copy_to_user(usr_buf, buf, sizeof(test) - size);
} else {
// Handle error
}
}
This code ensures that no uninitialized padding bits are copied to unprivileged users. The structure copied to user space is now a packed structure and the
copy_to_user()
function would need to unpack it to re-create the original, padded structure. | ## 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
P2
L3 | 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-scope entity with static storage duration, if applicable, is performed before its block is first entered. An implementation is permitted to perform early initialization of other block-scope variables with static or thread storage duration under the same conditions that an implementation is permitted to statically initialize a variable with static or thread storage duration in namespace scope (3.6.2). Otherwise such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.
Do not reenter a function during the initialization of a static variable declaration. If a function is reentered during the constant initialization of a static object inside that function, the behavior of the program is
undefined
. Infinite recursion is not required to trigger undefined behavior, the function need only recur once as part of the initialization. Due to thread-safe initialization of variables, a single, recursive call will often result in a
deadlock
due to locking a non-recursive synchronization primitive.
Additionally, the C++ Standard, [basic.start.init], paragraph 2, in part, states the following:
Dynamic initialization of a non-local variable with static storage duration is either ordered or unordered. Definitions of explicitly specialized class template static data members have ordered initialization. Other class template static data members (i.e., implicitly or explicitly instantiated specializations) have unordered initialization. Other non-local variables with static storage duration have ordered initialization. Variables with ordered initialization defined within a single translation unit shall be initialized in the order of their definitions in the translation unit. If a program starts a thread, the subsequent initialization of a variable is unsequenced with respect to the initialization of a variable defined in a different translation unit. Otherwise, the initialization of a variable is indeterminately sequenced with respect to the initialization of a variable defined in a different translation unit. If a program starts a thread, the subsequent unordered initialization of a variable is unsequenced with respect to every other dynamic initialization. Otherwise, the unordered initialization of a variable is indeterminately sequenced with respect to every other dynamic initialization.
Do not create an initialization interdependency between static objects with dynamic initialization unless they are ordered with respect to one another. Unordered initialization, especially prevalent across translation unit boundaries, results in
unspecified behavior
. | #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),
fact(12), fact(13), fact(14), fact(15), fact(16)
};
if (i < (sizeof(cache) / sizeof(int))) {
return cache[i];
}
return i > 0 ? i * fact(i - 1) : 1;
}
// file.h
#ifndef FILE_H
#define FILE_H
class Car {
int numWheels;
public:
Car() : numWheels(4) {}
explicit Car(int numWheels) : numWheels(numWheels) {}
int get_num_wheels() const { return numWheels; }
};
#endif // FILE_H
// file1.cpp
#include "file.h"
#include <iostream>
extern Car c;
int numWheels = c.get_num_wheels();
int main() {
std::cout << numWheels << std::endl;
}
// file2.cpp
#include "file.h"
Car get_default_car() { return Car(6); }
Car c = get_default_car();
## Noncompliant Code Example
This noncompliant example attempts to implement an efficient factorial function using caching. Because the initialization of the static local array
cache
involves recursion, the behavior of the function is undefined, even though the recursion is not infinite.
#FFCCCC
cpp
#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),
fact(12), fact(13), fact(14), fact(15), fact(16)
};
if (i < (sizeof(cache) / sizeof(int))) {
return cache[i];
}
return i > 0 ? i * fact(i - 1) : 1;
}
Implementation Details
In
Microsoft Visual Studio
2015 and
GCC
6.1.0, the recursive initialization of
cache
deadlocks while initializing the static variable in a thread-safe manner.
## Noncompliant Code Example
In this noncompliant code example, the value of
numWheels
in
file1.cpp
relies on
c
being initialized. However, because
c
is defined in a different translation unit (
file2.cpp
) than
numWheels
, there is no guarantee that
c
will be initialized by calling
get_default_car()
before
numWheels
is initialized by calling
c.get_num_wheels()
. This is often referred to as the "
static initialization order fiasco
," and the resulting behavior is unspecified.
#FFCCCC
cpp
// file.h
#ifndef FILE_H
#define FILE_H
class Car {
int numWheels;
public:
Car() : numWheels(4) {}
explicit Car(int numWheels) : numWheels(numWheels) {}
int get_num_wheels() const { return numWheels; }
};
#endif // FILE_H
// file1.cpp
#include "file.h"
#include <iostream>
extern Car c;
int numWheels = c.get_num_wheels();
int main() {
std::cout << numWheels << std::endl;
}
// file2.cpp
#include "file.h"
Car get_default_car() { return Car(6); }
Car c = get_default_car();
Implementation Details
The value printed to the standard output stream will often rely on the order in which the translation units are linked. For instance, with
Clang
3.8.0 on x86 Linux, the command
clang++ file1.cpp file2.cpp && ./a.out
will write
0
while
clang++ file2.cpp file1.cpp && ./a.out
will write
6
. | #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 ? i * fact(i - 1) : 1;
}
return cache[i];
}
return i > 0 ? i * fact(i - 1) : 1;
}
// file.h
#ifndef FILE_H
#define FILE_H
class Car {
int numWheels;
public:
Car() : numWheels(4) {}
explicit Car(int numWheels) : numWheels(numWheels) {}
int get_num_wheels() const { return numWheels; }
};
#endif // FILE_H
// file1.cpp
#include "file.h"
#include <iostream>
int &get_num_wheels() {
extern Car c;
static int numWheels = c.get_num_wheels();
return numWheels;
}
int main() {
std::cout << get_num_wheels() << std::endl;
}
// file2.cpp
#include "file.h"
Car get_default_car() { return Car(6); }
Car c = get_default_car();
## Compliant Solution
This compliant solution avoids initializing the static local array
cache
and instead relies on zero-initialization to determine whether each member of the array has been assigned a value yet and, if not, recursively computes its value. It then returns the cached value when possible or computes the value as needed.
#ccccff
cpp
#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 ? i * fact(i - 1) : 1;
}
return cache[i];
}
return i > 0 ? i * fact(i - 1) : 1;
}
## Compliant Solution
This compliant solution uses the "construct on first use" idiom to resolve the static initialization order issue. The code for
file.h
and
file2.cpp
are unchanged; only the static
numWheels
in
file1.cpp
is moved into the body of a function. Consequently, the initialization of
numWheels
is guaranteed to happen when control flows over the point of declaration, ensuring control over the order. The global object
c
is initialized before execution of
main()
begins, so by the time
get_num_wheels()
is called,
c
is guaranteed to have already been dynamically initialized.
#ccccff
cpp
// file.h
#ifndef FILE_H
#define FILE_H
class Car {
int numWheels;
public:
Car() : numWheels(4) {}
explicit Car(int numWheels) : numWheels(numWheels) {}
int get_num_wheels() const { return numWheels; }
};
#endif // FILE_H
// file1.cpp
#include "file.h"
#include <iostream>
int &get_num_wheels() {
extern Car c;
static int numWheels = c.get_num_wheels();
return numWheels;
}
int main() {
std::cout << get_num_wheels() << std::endl;
}
// file2.cpp
#include "file.h"
Car get_default_car() { return Car(6); }
Car c = get_default_car(); | ## 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
Likelihood
Detectable
Repairable
Priority
Level
DCL56-CPP
Low
Unlikely
Yes
No
P2
L3 | 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 terminates by throwing an exception, the behavior is undefined.
In these situations, the function must logically be declared
noexcept
because throwing an exception from the function can never have well-defined behavior. The C++ Standard, [except.spec], paragraph 15, states the following:
A deallocation function with no explicit exception-specification is treated as if it were specified with noexcept(true).
As such, deallocation functions (object, array, and placement forms at either global or class scope) must not terminate by throwing an exception. Do not declare such functions to be
noexcept(false)
. However, it is acceptable to rely on the implicit
noexcept(true)
specification or declare
noexcept
explicitly on the function signature.
Object destructors are likely to be called during stack unwinding as a result of an exception being thrown. If the destructor itself throws an exception, having been called as the result of an exception being thrown, then the function
std::terminate()
is called with the default effect of calling
std::abort()
[
ISO/IEC 14882-2014
]
.
When
std::abort()
is called, no further objects are destroyed, resulting in an indeterminate program state and undefined behavior. Do not terminate a destructor by throwing an exception.
The C++ Standard, [class.dtor], paragraph 3, states [
ISO/IEC 14882-2014
] the following:
A declaration of a destructor that does not have an exception-specification is implicitly considered to have the same exception-specification as an implicit declaration.
An implicit declaration of a destructor is considered to be
noexcept(true)
according to [except.spec], paragraph 14. As such, destructors must not be declared
noexcept(false)
but may instead rely on the implicit
noexcept(true)
or declare
noexcept
explicitly.
Any
noexcept
function that terminates by throwing an exception violates
. | #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) {
// Normal processing
if (has_error() && !std::uncaught_exception()) {
throw std::logic_error("Something bad");
}
}
};
// Assume that this class is provided by a 3rd party and it is not something
// that can be modified by the user.
class Bad {
~Bad() noexcept(false);
};
class SomeClass {
Bad bad_member;
public:
~SomeClass()
try {
// ...
} catch(...) {
// Handle the exception thrown from the Bad destructor.
}
};
#include <stdexcept>
bool perform_dealloc(void *);
void operator delete(void *ptr) noexcept(false) {
if (perform_dealloc(ptr)) {
throw std::logic_error("Something bad");
}
}
## Noncompliant Code Example
In this noncompliant code example, the class destructor does not meet the implicit
noexcept
guarantee because it may throw an exception even if it was called as the result of an exception being thrown. Consequently, it is declared as
noexcept(false)
but still can trigger
undefined behavior
.
#FFcccc
cpp
#include <stdexcept>
class S {
bool has_error() const;
public:
~S() noexcept(false) {
// Normal processing
if (has_error()) {
throw std::logic_error("Something bad");
}
}
};
## Noncompliant Code Example (std::uncaught_exception())
Use of
std::uncaught_exception()
in the destructor solves the termination problem by avoiding the propagation of the exception if an existing exception is being processed, as demonstrated in this noncompliant code example. However, by circumventing normal destructor processing, this approach may keep the destructor from releasing important resources.
#FFcccc
cpp
#include <exception>
#include <stdexcept>
class S {
bool has_error() const;
public:
~S() noexcept(false) {
// Normal processing
if (has_error() && !std::uncaught_exception()) {
throw std::logic_error("Something bad");
}
}
};
## Noncompliant Code Example(function-try-block)
This noncompliant code example, as well as the following compliant solution, presumes the existence of a
Bad
class with a destructor that can throw. Although the class violates this rule, it is presumed that the class cannot be modified to comply with this rule.
#FFcccc
cpp
// Assume that this class is provided by a 3rd party and it is not something
// that can be modified by the user.
class Bad {
~Bad() noexcept(false);
};
To safely use the
Bad
class, the
SomeClass
destructor attempts to handle exceptions thrown from the
Bad
destructor by absorbing them.
#FFcccc
cpp
class SomeClass {
Bad bad_member;
public:
~SomeClass()
try {
// ...
} catch(...) {
// Handle the exception thrown from the Bad destructor.
}
};
However, the C++ Standard, [except.handle], paragraph 15 [
ISO/IEC 14882-2014
], in part, states the following:
The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor.
Consequently, the caught exception will inevitably escape from the
SomeClass
destructor because it is implicitly rethrown when control reaches the end of the
function-try-block
handler.
## Noncompliant Code Example
In this noncompliant code example, a global deallocation is declared
noexcept(false)
and throws an exception if some conditions are not properly met. However, throwing from a deallocation function results in
undefined behavior
.
#FFcccc
cpp
#include <stdexcept>
bool perform_dealloc(void *);
void operator delete(void *ptr) noexcept(false) {
if (perform_dealloc(ptr)) {
throw std::logic_error("Something bad");
}
} | 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 implicitly rethrown, but an explicit
// return statement will prevent that from happening.
return;
}
};
#include <cstdlib>
#include <stdexcept>
bool perform_dealloc(void *);
void log_failure(const char *);
void operator delete(void *ptr) noexcept(true) {
if (perform_dealloc(ptr)) {
log_failure("Deallocation of pointer failed");
std::exit(1); // Fail, but still call destructors
}
}
## Compliant Solution
A destructor should perform the same way whether or not there is an active exception. Typically, this means that it should invoke only operations that do not throw exceptions, or it should handle all exceptions and not rethrow them (even implicitly). This compliant solution differs from the previous noncompliant code example by having an explicit
return
statement in the
SomeClass
destructor. This statement prevents control from reaching the end of the exception handler. Consequently, this handler will catch the exception thrown by
Bad::~Bad()
when
bad_member
is destroyed. It will also catch any exceptions thrown within the compound statement of the
function-try-block
, but the
SomeClass
destructor will not terminate by throwing an exception.
#ccccff
cpp
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 implicitly rethrown, but an explicit
// return statement will prevent that from happening.
return;
}
};
## Compliant Solution
The compliant solution does not throw exceptions in the event the deallocation fails but instead fails as gracefully as possible.
#ccccff
cpp
#include <cstdlib>
#include <stdexcept>
bool perform_dealloc(void *);
void log_failure(const char *);
void operator delete(void *ptr) noexcept(true) {
if (perform_dealloc(ptr)) {
log_failure("Deallocation of pointer failed");
std::exit(1); // Fail, but still call destructors
}
} | ## 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 MyNamespace {
int length;
}
namespace MyNamespace {
int width;
}
void f() {
MyNamespace::length = MyNamespace::width = 12;
}
The standard library introduces the namespace
std
for standards-provided declarations such as
std::string
,
std::vector
, and
std::for_each
. However, it is
undefined behavior
to introduce new declarations in namespace
std
except under special circumstances. The C++ Standard, [namespace.std], paragraphs 1 and 2 [
ISO/IEC 14882-2014
], states the following:
1
The behavior of a C++ program is undefined if it adds declarations or definitions to namespace
std
or to a namespace within namespace
std
unless otherwise specified. A program may add a template specialization for any standard library template to namespace
std
only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.
2
The behavior of a C++ program is undefined if it declares
— an explicit specialization of any member function of a standard library class template, or
— an explicit specialization of any member function template of a standard library class or class template, or
— an explicit or partial specialization of any member class template of a standard library class or class template.
In addition to restricting extensions to the the namespace
std
, the C++ Standard, [namespace.posix], paragraph 1, further states the following:
The behavior of a C++ program is undefined if it adds declarations or definitions to namespace
posix
or to a namespace within namespace
posix
unless otherwise specified. The namespace
posix
is reserved for use by ISO/IEC 9945 and other POSIX standards.
Do not add declarations or definitions to the standard namespaces
std
or
posix
, or to a namespace contained therein, except for a template specialization that depends on a user-defined type that meets the standard library requirements for the original template.
The Library Working Group, responsible for the wording of the Standard Library section of the C++ Standard, has an unresolved
issue
on the definition of
user-defined type
. Although the Library Working Group has no official stance on the definition [
INCITS 2014
], we define it to be any
class
,
struct
,
union
, or
enum
that is not defined within namespace
std
or a namespace contained within namespace
std
. Effectively, it is a user-provided type instead of a standard library–provided type. | 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<string, MyString, string> {
string operator()(const string &lhs, const MyString &rhs) const {
return lhs + rhs.get_data();
}
};
}
void f() {
std::string s1("My String");
MyString s2(" + Your String");
std::plus<std::string> p;
std::cout << p(s1, s2) << std::endl;
}
## Noncompliant Code Example
## In this noncompliant code example, the declaration ofxis added to the namespacestd, resulting inundefined behavior.
#FFCCCC
cpp
namespace std {
int x;
}
## Noncompliant Code Example
In this noncompliant code example, a template specialization of
std::plus
is added to the namespace
std
in an attempt to allow
std::plus
to concatenate a
std::string
and
MyString
object. However, because the template specialization is of a standard library–provided type (
std::string
), this code results in undefined behavior.
#FFCCCC
cpp
#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<string, MyString, string> {
string operator()(const string &lhs, const MyString &rhs) const {
return lhs + rhs.get_data();
}
};
}
void f() {
std::string s1("My String");
MyString s2(" + Your String");
std::plus<std::string> p;
std::cout << p(s1, s2) << std::endl;
} | 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::string> {
std::string operator()(const std::string &lhs, const MyString &rhs) const {
return lhs + rhs.get_data();
}
};
void f() {
std::string s1("My String");
MyString s2(" + Your String");
my_plus p;
std::cout << p(s1, s2) << std::endl;
}
#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<MyString> {
MyString operator()(const MyString &lhs, const MyString &rhs) const {
return lhs.get_data() + rhs.get_data();
}
};
}
void f() {
std::string s1("My String");
MyString s2(" + Your String");
std::plus<MyString> p;
std::cout << p(s1, s2).get_data() << std::endl;
}
## Compliant Solution
This compliant solution assumes the intention of the programmer was to place the declaration of
x
into a namespace to prevent collisions with other global identifiers. Instead of placing the declaration into the namespace
std
, the declaration is placed into a namespace without a reserved name.
#ccccff
cpp
namespace nonstd {
int x;
}
## Compliant Solution
The interface for
std::plus
requires that both arguments to the function call operator and the return type are of the same type. Because the attempted specialization in the noncompliant code example results in
undefined behavior
, this compliant solution defines a new
std::binary_function
derivative that can add a
std::string
to a
MyString
object without requiring modification of the namespace
std
.
#ccccff
cpp
#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::string> {
std::string operator()(const std::string &lhs, const MyString &rhs) const {
return lhs + rhs.get_data();
}
};
void f() {
std::string s1("My String");
MyString s2(" + Your String");
my_plus p;
std::cout << p(s1, s2) << std::endl;
}
## Compliant Solution
In this compliant solution, a specialization of
std::plus
is added to the
std
namespace, but the specialization depends on a user-defined type and meets the Standard Template Library requirements for the original template, so it complies with this rule. However, because
MyString
can be constructed from
std::string
, this compliant solution involves invoking a converting constructor whereas the previous compliant solution does not.
#ccccff
cpp
#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<MyString> {
MyString operator()(const MyString &lhs, const MyString &rhs) const {
return lhs.get_data() + rhs.get_data();
}
};
}
void f() {
std::string s1("My String");
MyString s2(" + Your String");
std::plus<MyString> p;
std::cout << p(s1, s2).get_data() << std::endl;
} | ## Risk Assessment
Altering the standard namespace can cause
undefined behavior
in the C++ standard library.
Rule
Severity
Likelihood
Detectable
Repairable
Priority
Level
DCL58-CPP
High
Unlikely
Yes
No
P6
L2 | SEI CERT C++ Coding Standard > 2 Rules > Rule 01. Declarations and Initialization (DCL) |
Dataset Card for SEI CERT C++ Coding Standard (Wiki rules)
Structured export of the SEI CERT C++ Coding Standard from the SEI wiki.
Dataset Details
Dataset Description
Tabular snapshot of CERT C++ secure coding rules with narrative text and illustrative compliant / noncompliant code where published on the wiki.
- Curated by: Derived from public SEI CERT wiki pages; packaged as CSV by the dataset maintainer.
- Funded by [optional]: [More Information Needed]
- Shared by [optional]: [More Information Needed]
- Language(s) (NLP): English (rule text and embedded code).
- License: Compilation distributed as
other; confirm terms with CMU SEI for redistribution.
Dataset Sources [optional]
- Repository: https://wiki.sei.cmu.edu/confluence/display/seccode/SEI+CERT+Coding+Standards
- Paper [optional]: SEI CERT C++ Coding Standard
- Demo [optional]: [More Information Needed]
Uses
Direct Use
C++ security linting research, courseware, and retrieval-augmented assistants.
Out-of-Scope Use
Not authoritative for compliance audits without verifying against the current standard.
Dataset Structure
All rows share the same columns (scraped from the SEI CERT Confluence wiki):
| Column | Description |
|---|---|
language |
Language identifier for the rule set |
page_id |
Confluence page id |
page_url |
Canonical wiki URL for the rule page |
chapter |
Chapter label when present |
section |
Section label when present |
rule_id |
Rule identifier (e.g. API00-C, CON50-J) |
title |
Short rule title |
intro |
Normative / explanatory text |
noncompliant_code |
Noncompliant example(s) when present |
compliant_solution |
Compliant example(s) when present |
risk_assessment |
Risk / severity notes when present |
breadcrumb |
Wiki breadcrumb trail when present |
Dataset Creation
Curation Rationale
Expose CERT C++ guidance in a uniform schema for tooling and ML workflows.
Source Data
Data Collection and Processing
Wiki scrape normalized to the shared CSV schema used across SEI CERT language exports.
Who are the source data producers?
[More Information Needed]
Annotations [optional]
Annotation process
[More Information Needed]
Who are the annotators?
[More Information Needed]
Personal and Sensitive Information
[More Information Needed]
Bias, Risks, and Limitations
[More Information Needed]
Recommendations
Users should be made aware of the risks, biases and limitations of the dataset. More information needed for further recommendations.
Citation [optional]
BibTeX:
[More Information Needed]
APA:
[More Information Needed]
Glossary [optional]
[More Information Needed]
More Information [optional]
[More Information Needed]
Dataset Card Authors [optional]
[More Information Needed]
Dataset Card Contact
[More Information Needed]
- Downloads last month
- 10