Skip to main content
Be Bitwise
C++Security-Focused C++

Secure Coding Patterns

C++ ships features that, used religiously, defang whole categories of bugs. Const correctness, [[nodiscard]], std::optional, and a steady refusal to invoke undefined behaviour — that's the bedrock of writing C++ that doesn't rot into a CVE.

Const Correctness

Don't read const as a comment. It's a contract the compiler enforces for you:

cpp
class Database {
std::map<std::string, std::string> data_;
public:
// const: promises not to modify state
std::optional<std::string> get(const std::string& key) const {
auto it = data_.find(key);
if (it != data_.end()) return it->second;
return std::nullopt;
}
// Non-const: may modify state
void set(const std::string& key, std::string value) {
data_[key] = std::move(value);
}
};
void read_only_operation(const Database& db) {
// db.set("key", "val"); // ERROR: cannot call non-const on const ref
auto val = db.get("key"); // OK: get is const
}
Key Concept

Default to const everywhere — parameters, locals, member functions, return types — and only peel it off when something genuinely has to mutate. The bug surface shrinks, and reasoning about shared state across threads gets dramatically easier.

[[nodiscard]]: Do Not Ignore Important Returns

cpp
[[nodiscard]] bool save_to_disk(const std::string& data) {
// Returns false on failure
return write_file("data.bin", data);
}
// The compiler warns if you ignore the return value:
save_to_disk(data); // WARNING: ignoring return value of nodiscard function
// Correct usage:
if (!save_to_disk(data)) {
handle_error();
}

Reach for [[nodiscard]] on:

  • Functions that hand back error status.
  • Factory functions — ignore the return and you've leaked.
  • Pure functions whose entire purpose is the result.

C++20 even lets you attach a reason: [[nodiscard("Check for write errors")]].

std::optional for Nullable Values

Skip null pointers and magic sentinels. std::optional says "maybe a value, maybe not" out loud:

cpp
#include <charconv>
#include <optional>
#include <string_view>
std::optional<int> parse_port(std::string_view input) {
int port = 0;
auto [end, ec] = std::from_chars(input.data(), input.data() + input.size(), port);
// Reject parse errors and trailing junk: "8080abc" is not a port
if (ec != std::errc{} || end != input.data() + input.size()) return std::nullopt;
if (port < 1 || port > 65535) return std::nullopt;
return port;
}
void use_it() {
auto port = parse_port("8080");
if (port) {
connect_to(*port); // Dereference with *
} else {
use_default_port();
}
// Or with value_or
int p = parse_port("invalid").value_or(80);
}

The obvious version, std::stoi inside a try, is looser than it looks: stoi skips leading whitespace and stops at the first non-digit, so "8080abc" comes back as 8080. std::from_chars doesn't throw or skip anything, and comparing end with the end of the input makes the whole string count.

Expected (Error Handling Without Exceptions)

C++23 ships std::expected properly, but the pattern works on older standards if you roll it yourself:

cpp
#include <variant>
#include <string>
template <typename T, typename E = std::string>
class Expected {
std::variant<T, E> data_;
public:
Expected(T value) : data_(std::move(value)) {}
Expected(E error) : data_(std::move(error)) {}
bool has_value() const { return data_.index() == 0; }
explicit operator bool() const { return has_value(); }
T& value() { return std::get<0>(data_); }
const T& value() const { return std::get<0>(data_); }
E& error() { return std::get<1>(data_); }
const E& error() const { return std::get<1>(data_); }
};
Expected<int> divide(int a, int b) {
if (b == 0) return Expected<int>(std::string("Division by zero"));
return Expected<int>(a / b);
}
What happens if someone writes Expected<std::string>?

It doesn't compile. With T and E both std::string, the two constructors have the same signature, so the class can't be instantiated at all. std::expected avoids this by making you wrap errors in std::unexpected, which keeps the two paths distinct whatever the types are.

Avoiding Undefined Behavior

C++ has even more ways to summon undefined behaviour than C does. The greatest hits:

cpp
#include <climits> // INT_MAX
// UB 1: Signed integer overflow
int x = INT_MAX;
x = x + 1; // UB! Use unsigned or check first
// UB 2: Null pointer dereference
int* p = nullptr;
int val = *p; // UB!
// Pitfall 3: Use after move
std::string s = "hello";
std::string s2 = std::move(s);
std::cout << s.size(); // Valid but unspecified (s is in a "valid but unspecified" state)
// UB 4: Iterator invalidation
std::vector<int> v = {1, 2, 3};
for (auto it = v.begin(); it != v.end(); ++it) {
if (*it == 2) v.push_back(4); // UB: invalidates iterators
}
// UB 5: Dangling reference
const std::string& danger() {
std::string local = "oops";
return local; // Dangling reference to destroyed object
}

Integer overflow in a size calculation sits behind a long run of heap-overflow CVEs: an attacker supplies a count, the multiply wraps, and a tiny buffer gets a huge amount written into it. Unsigned arithmetic wraps instead of being undefined, but the answer is just as wrong. Predict what the naive version asks malloc for on the second count.

Try itAdd a uint64_t field to Record and find the smallest count that wraps the naive multiply now. __builtin_mul_overflow is a GCC and Clang extension; C23 standardises the same check as ckd_mul.
C++ (GCC 9.2.0)

Safe Casting

cpp
// AVOID: C-style casts (no checking)
int* p = (int*)some_void_ptr;
// PREFER: C++ casts (explicit intent)
// static_cast: compile-time checked conversions
double d = 3.14;
int i = static_cast<int>(d);
// dynamic_cast: runtime-checked downcasts (requires virtual functions)
Base* base = get_object();
if (auto* derived = dynamic_cast<Derived*>(base)) {
derived->specific_method();
}
// reinterpret_cast: dangerous, but explicit
// Viewing any object as bytes through char* is allowed
auto* bytes = reinterpret_cast<const char*>(&value);
// Reading a float through a uint32_t* breaks strict aliasing: UB
float f = 1.0f;
// uint32_t bits = *reinterpret_cast<uint32_t*>(&f); // UB
uint32_t bits = std::bit_cast<uint32_t>(f); // C++20, <bit>; memcpy before that
// const_cast: removing const (almost never appropriate)
// If you need this, your design is probably wrong

Watch for the conversions that need no cast at all. int i = d; or passing a size_t length into an int parameter silently narrows, and a 5 GB length becomes a small or negative number. Brace initialisation turns that into a compile error (int i{d}; won't build), and -Wconversion warns about the rest. When the value comes from outside, check it fits before converting: C++20's std::in_range<int>(n) does exactly that.

Defensive Constructor Patterns

cpp
class Config {
int port_;
std::string host_;
std::chrono::seconds timeout_;
public:
// Validate in constructor
Config(int port, std::string host, std::chrono::seconds timeout)
: port_(port), host_(std::move(host)), timeout_(timeout) {
if (port_ < 1 || port_ > 65535) {
throw std::invalid_argument("Port out of range");
}
if (host_.empty()) {
throw std::invalid_argument("Host cannot be empty");
}
if (timeout_.count() < 0) {
throw std::invalid_argument("Timeout cannot be negative");
}
}
// Getters return const refs or values
int port() const { return port_; }
const std::string& host() const { return host_; }
};

Enum Class for Type Safety

cpp
// BAD: C-style enum (implicit conversion to int)
enum Color { RED, GREEN, BLUE };
int x = RED; // Compiles, but probably wrong
// GOOD: scoped enum
enum class Permission : uint8_t {
Read = 1,
Write = 2,
Execute = 4,
};
// Cannot accidentally convert to int
// int x = Permission::Read; // ERROR
// Must be explicit
auto p = Permission::Read;

Summary

A checklist worth taping above the keyboard:

  1. const whatever shouldn't change — that's most things.
  2. [[nodiscard]] whenever ignoring the return is a bug.
  3. std::optional over null pointers and sentinel values.
  4. Smart pointers over raw new/delete.
  5. Scoped enums (enum class) over plain enum.
  6. C++ casts (static_cast, dynamic_cast) over C-style casts.
  7. Validate inputs in constructors and at every public boundary.
  8. Know what's UB. When in doubt, run with sanitisers.