{
  "slug": "secure-cpp",
  "topic": "Secure C and C++",
  "status": "published",
  "order": 47,
  "capability": "coding/cpp",
  "title": "C and C++: how safe can you get without a rewrite?",
  "short": "Ship every build with the OpenSSF hardening flags and a bounds-checked standard library (0.3% overhead at Google), fuzz parsers under ASan and write new components in a memory-safe language.",
  "answer": "Before your next release, build with the OpenSSF hardening flags and a bounds-checked standard library, and run tests and fuzzers under ASan and UBSan in CI. Write new components in a memory-safe language, and judge each change by whether it checks the size, owner and lifetime of memory that outside data reaches.",
  "audience": "Developers and tech leads maintaining production C and C++, and the security people who review it",
  "version": "1.0",
  "lastReviewed": "2026-11-05",
  "reviewEveryDays": 30,
  "blocks": [
    {
      "type": "ranked",
      "id": "first",
      "title": "If you only do five things",
      "navTitle": "Five things",
      "intro": "Seven of the 2025 CWE Top 25 are memory-safety weaknesses[^cwe25]. Writing new code in memory-safe languages cut them from 76% of Android's vulnerabilities in 2019 to under 20% in 2025[^gsource][^android].",
      "items": [
        {
          "title": "Build every release with the OpenSSF hardening flags.",
          "text": "For GCC and Clang these include `-D_FORTIFY_SOURCE=3`, `-fstack-protector-strong`, `-fstack-clash-protection`, `-ftrivial-auto-var-init=zero`, PIE and full RELRO[^openssf]; GCC's `-fhardened` sets them all on GNU/Linux[^gccinst]. On MSVC, add `/guard:cf`[^mscfg]."
        },
        {
          "title": "Bounds-check the standard library in production.",
          "text": "Define `_GLIBCXX_ASSERTIONS`, set libc++'s mode to `_LIBCPP_HARDENING_MODE_FAST`[^openssf][^libcxx] or define `_MSVC_STL_HARDENING=1`[^msstl]. At Google, hardened libc++ cost 0.3% on average, found over 1,000 bugs and cut segfaults by 30%[^gretro]."
        },
        {
          "title": "Run every test under ASan and UBSan.",
          "text": "`-fsanitize=address` finds out-of-bounds access and use after free at about half speed[^asan], `-fsanitize=undefined` signed overflow and other undefined behavior[^ubsan]. Build those jobs with `-U_FORTIFY_SOURCE`, as distros often enable it[^openssf]."
        },
        {
          "title": "Fuzz every parser of outside data.",
          "text": "Give each file format, protocol and decoder a libFuzzer target, and run it on every pull request with ClusterFuzzLite under ASan, MSan and UBSan[^cflite]."
        },
        {
          "title": "Write new components in a memory-safe language.",
          "text": "New code holds most bugs: five-year-old code has 3.4 to 7.4 times lower vulnerability density[^gsource]. For critical-infrastructure products, CISA and the FBI wanted a published memory-safety roadmap by the end of 2025[^cisabad]."
        }
      ]
    },
    {
      "type": "steps",
      "id": "review",
      "title": "Review a C or C++ pull request",
      "navTitle": "Review",
      "items": [
        {
          "title": "Does a length, count or offset come from the input?",
          "text": "Check it against the bytes left and the destination's size before any copy, index or allocation."
        },
        {
          "title": "Can a size calculation wrap?",
          "text": "Look for `*` and `+` on sizes, `int` lengths and signed-to-unsigned casts. Ask for `__builtin_mul_overflow`[^gccovf]."
        },
        {
          "title": "Who owns each pointer, and can anything outlive it?",
          "text": "Check raw `new`, `delete` and `free`, stored `string_view` and `span` members, and callbacks that capture `this` or `&`."
        },
        {
          "title": "Is every error code and union tag checked?",
          "text": "Ask for `[[nodiscard]]` on functions that return errors and a tag check before each union read."
        },
        {
          "title": "Does it switch off a check?",
          "text": "Warning pragmas, `no_sanitize`, `_LIBCPP_HARDENING_MODE_NONE`, `[[indeterminate]]` and `/GS-` need a second reviewer."
        }
      ]
    },
    {
      "type": "list",
      "id": "traps",
      "title": "C and C++ traps and what to use instead",
      "navTitle": "Traps",
      "span": "full",
      "items": [
        "**`memcpy(buf, p, len)` with `len` from the input.** OpenSSL copied an AEAD IV into a fixed-size stack buffer without a length check, before any authentication (CVE-2025-15467, high)[^openssl]. Check each length against the destination and the bytes left; `_FORTIFY_SOURCE=3` catches it only if it knows the size[^openssf].",
        "**`n * size` and `len + 1` in size calculations.** Unsigned arithmetic wraps, and signed overflow is undefined, so the compiler may delete your overflow check[^openssf]. Integer overflows in Onigmo, Ruby's regex engine, could let crafted patterns run code on GitLab (CVE-2026-97229, exploited)[^ruby][^kev]. Use `__builtin_mul_overflow`[^gccovf].",
        "**Error codes that let a decoder keep going.** Brotli's decoder treated an invalid block switch as a need for more input and kept appending to an eight-byte buffer (CVE-2026-111497, exploited)[^nodejs][^kev]. Treat format errors as final, bound every append and mark error returns `[[nodiscard]]`.",
        "**Ownership an API leaves unclear.** OpenSSL's `PKCS7_verify()` freed a BIO its caller still owned, so the caller's `BIO_free()` became a use after free (CVE-2026-45447, high)[^openssl]. Own with `std::unique_ptr`, don't keep a `std::string_view` past its owner, and in C document who frees what.",
        "**Reading a union member as the wrong type.** OpenSSL read an `ASN1_TYPE` union member without checking its type (CVE-2026-22796)[^openssl], and CISA added type confusion bugs in V8 and Windows to its exploited list in 2026[^kev]. Check the tag first; in C++ use `std::variant`.",
        "**`printf(msg)` and your own logging wrappers.** OpenSSL passed a peer-supplied name as the format string to `ERR_raise_data()`, so `CN=%s%n` crashed CMP clients (CVE-2026-63073)[^openssl]. Pass data through `\"%s\"`, and mark wrappers `format(printf, m, n)` to get printf's checks[^gccattr]."
      ]
    },
    {
      "type": "list",
      "id": "tools",
      "title": "Tools that catch it",
      "navTitle": "Tools",
      "items": [
        "**Sanitizers.** ASan (about 2x slower), UBSan, MSan for uninitialized reads (every library instrumented, and no `-ftrivial-auto-var-init`, which masks them) and TSan for data races, which can't run with ASan[^asan][^msan][^openssf]. MSVC has `/fsanitize=address`[^msasan].",
        "**Fuzzers.** libFuzzer now gets only bug fixes[^libfuzzer]; ClusterFuzzLite runs it on pull requests and in batch jobs[^cflite].",
        "**Warnings.** `-Wall`, `-Wextra`, `-Wformat=2`, `-Wconversion` and `-Werror=format-security`[^openssf]. In C++, Clang's `-Wunsafe-buffer-usage` flags buffer access through raw pointers[^safebuf]. On MSVC, `/sdl` makes uninitialized-variable warnings errors[^mssdl]."
      ]
    },
    {
      "type": "list",
      "id": "changed",
      "title": "What changed in 2026",
      "navTitle": "What changed",
      "items": [
        "**GCC 16 (30 April) zero-initializes locals under `-std=c++26`** and now defaults to `-std=gnu++20`[^gcc16][^gccopt].",
        "**Clang 23 added `-Wlifetime-safety`,** which detects use after free within a function. Add it to CI[^clang23].",
        "**OpenSSL published 63 CVEs in 2026, against 6 in 2025;** all three High ones are memory-safety bugs[^openssl]. 3.0 and 3.6 are now out of support; 3.5 is supported until April 2030, 4.0 until May 2027[^opensslrel].",
        "**CISA added an exploited Brotli overflow on 27 October.** Update every copy, vendored ones too, to 1.0.10, 1.1.1 or 1.2.1[^cvebrotli][^kev]."
      ]
    },
    {
      "type": "list",
      "id": "skip",
      "title": "What you can skip",
      "items": [
        "**Waiting for C++26.** It isn't final yet[^p4433], its library hardening standardizes checks the three major libraries already ship[^p3471], and `-ftrivial-auto-var-init=zero` initializes locals today[^openssf].",
        "**Rewriting stable code at once.** Vulnerabilities decay as code ages[^gsource]: harden old code and rewrite the parsers that take outside data.",
        "**Valgrind in CI.** Sanitizers find similar bugs at a 2x to 4x slowdown, against up to 20x to 50x[^openssf]."
      ]
    },
    {
      "type": "list",
      "id": "mistakes",
      "title": "Mistakes that cost the most",
      "navTitle": "Mistakes",
      "items": [
        "**Checks only debug builds get.** GCC 15's libstdc++ enables its assertions by default only in unoptimized builds[^gcc15], and `_FORTIFY_SOURCE` needs `-O1` or higher[^openssf]. Set both in release builds.",
        "**Shipping sanitizer runtimes.** Their environment-variable options can let attackers clobber root-owned files through setuid binaries. Only UBSan's minimal runtime or trap mode belongs in production[^openssf][^ubsan]."
      ]
    },
    {
      "type": "columns",
      "id": "by-size",
      "title": "What this looks like for your code",
      "navTitle": "By codebase",
      "span": "full",
      "columns": [
        {
          "title": "New project",
          "items": [
            "Ask first whether it can be Rust or another memory-safe language; see the Rust sheet.",
            "If it must be C++, use `std::span`, `std::unique_ptr` and `-Wunsafe-buffer-usage`[^safebuf].",
            "Start with the OpenSSF flags, a hardened library, sanitizer jobs and a fuzz target per parser."
          ]
        },
        {
          "title": "Existing codebase",
          "items": [
            "Roll out hardening as Google did: tests first, then pre-production, then production over months[^gretro].",
            "Replace `[0]` and `[1]` trailing arrays with `[]`, then add `-fstrict-flex-arrays=3`[^openssf].",
            "Fuzz first the code CISA calls priority, network-facing and crypto[^cisabad]; publish a date after which new code is memory-safe[^cisaroad]."
          ]
        },
        {
          "title": "High-assurance or regulated",
          "items": [
            "Follow Chromium's Rule of 2: of untrusted input, unsafe language and high privilege, pick two at most[^ruleof2].",
            "Use libc++ extensive mode where benchmarks allow[^libcxx], and MSan with every library instrumented[^msan].",
            "On Arm cores with MTE, tag stack memory with GCC 16's `-fsanitize=memtag`[^gcc16]."
          ]
        }
      ]
    }
  ],
  "changes": [
    {
      "date": "2026-11-05",
      "version": "1.0",
      "text": "Published after a copy edit and a source-by-source fact check, which limited Google's overhead figure to hardened libc++, warned that zero-initialization masks MemorySanitizer findings, added the open C++26 ballot and updated OpenSSL's supported versions."
    },
    {
      "date": "2026-11-05",
      "version": "0.1",
      "text": "First draft, based on the OpenSSF compiler hardening guide, GCC, Clang, libc++ and MSVC docs, Google's memory-safety data, CISA and FBI guidance, OpenSSL advisories, the KEV catalog and the 2025 CWE Top 25."
    }
  ],
  "sources": [
    {
      "id": "cwe25",
      "title": "2025 CWE Top 25",
      "publisher": "MITRE",
      "date": "updated 15 Dec 2025",
      "url": "https://cwe.mitre.org/top25/archive/2025/2025_cwe_top25.html"
    },
    {
      "id": "gsource",
      "title": "Eliminating Memory Safety Vulnerabilities at the Source",
      "publisher": "Google",
      "date": "25 Sep 2024",
      "url": "https://security.googleblog.com/2024/09/eliminating-memory-safety-vulnerabilities-Android.html"
    },
    {
      "id": "android",
      "title": "Rust in Android: move fast and fix things",
      "publisher": "Google",
      "date": "13 Nov 2025",
      "url": "https://blog.google/security/rust-in-android-move-fast-fix-things/"
    },
    {
      "id": "openssf",
      "title": "Compiler Options Hardening Guide for C and C++",
      "publisher": "OpenSSF",
      "date": "20 Aug 2026",
      "url": "https://best.openssf.org/Compiler-Hardening-Guides/Compiler-Options-Hardening-Guide-for-C-and-C++.html"
    },
    {
      "id": "gccinst",
      "title": "Instrumentation Options",
      "publisher": "GCC manual",
      "date": "checked 5 Nov 2026",
      "url": "https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html"
    },
    {
      "id": "mscfg",
      "title": "/guard (Enable Control Flow Guard)",
      "publisher": "Microsoft Learn",
      "date": "checked 5 Nov 2026",
      "url": "https://learn.microsoft.com/en-us/cpp/build/reference/guard-enable-control-flow-guard"
    },
    {
      "id": "libcxx",
      "title": "libc++ Hardening Modes",
      "publisher": "LLVM",
      "date": "checked 5 Nov 2026",
      "url": "https://libcxx.llvm.org/Hardening.html"
    },
    {
      "id": "msstl",
      "title": "STL Hardening",
      "publisher": "Microsoft STL wiki",
      "date": "4 Mar 2026",
      "url": "https://github.com/microsoft/STL/wiki/STL-Hardening"
    },
    {
      "id": "gretro",
      "title": "Retrofitting spatial safety to hundreds of millions of lines of C++",
      "publisher": "Google",
      "date": "15 Nov 2024",
      "url": "https://security.googleblog.com/2024/11/retrofitting-spatial-safety-to-hundreds.html"
    },
    {
      "id": "asan",
      "title": "AddressSanitizer",
      "publisher": "Clang docs",
      "date": "checked 5 Nov 2026",
      "url": "https://clang.llvm.org/docs/AddressSanitizer.html"
    },
    {
      "id": "ubsan",
      "title": "UndefinedBehaviorSanitizer",
      "publisher": "Clang docs",
      "date": "checked 5 Nov 2026",
      "url": "https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html"
    },
    {
      "id": "cflite",
      "title": "ClusterFuzzLite",
      "publisher": "Google",
      "date": "checked 5 Nov 2026",
      "url": "https://google.github.io/clusterfuzzlite/"
    },
    {
      "id": "cisabad",
      "title": "Product Security Bad Practices, version 2",
      "publisher": "CISA and FBI",
      "date": "Jan 2025",
      "url": "https://www.ic3.gov/CSA/2025/250117.pdf"
    },
    {
      "id": "gccovf",
      "title": "Integer Overflow Builtins",
      "publisher": "GCC manual",
      "date": "checked 5 Nov 2026",
      "url": "https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html"
    },
    {
      "id": "openssl",
      "title": "Vulnerabilities",
      "publisher": "OpenSSL",
      "date": "checked 5 Nov 2026",
      "url": "https://openssl-library.org/news/vulnerabilities/"
    },
    {
      "id": "ruby",
      "title": "Regexp compilation fixes related to GitLab's CVEs",
      "publisher": "Ruby",
      "date": "23 Oct 2026",
      "url": "https://www.ruby-lang.org/en/news/2026/10/23/regexp-fixes-for-gitlab-cves/"
    },
    {
      "id": "kev",
      "title": "Known Exploited Vulnerabilities Catalog",
      "publisher": "CISA",
      "date": "data feed, 4 Nov 2026",
      "url": "https://github.com/cisagov/kev-data"
    },
    {
      "id": "nodejs",
      "title": "October 21, 2026 Security Releases",
      "publisher": "Node.js",
      "date": "21 Oct 2026",
      "url": "https://nodejs.org/en/blog/vulnerability/october-2026-security-releases"
    },
    {
      "id": "gccattr",
      "title": "Common Attributes",
      "publisher": "GCC manual",
      "date": "checked 5 Nov 2026",
      "url": "https://gcc.gnu.org/onlinedocs/gcc/Common-Attributes.html"
    },
    {
      "id": "msan",
      "title": "MemorySanitizer",
      "publisher": "Clang docs",
      "date": "checked 5 Nov 2026",
      "url": "https://clang.llvm.org/docs/MemorySanitizer.html"
    },
    {
      "id": "msasan",
      "title": "AddressSanitizer",
      "publisher": "Microsoft Learn",
      "date": "checked 5 Nov 2026",
      "url": "https://learn.microsoft.com/en-us/cpp/sanitizers/asan"
    },
    {
      "id": "libfuzzer",
      "title": "libFuzzer",
      "publisher": "LLVM",
      "date": "checked 5 Nov 2026",
      "url": "https://llvm.org/docs/LibFuzzer.html"
    },
    {
      "id": "safebuf",
      "title": "C++ Safe Buffers",
      "publisher": "Clang docs",
      "date": "checked 5 Nov 2026",
      "url": "https://clang.llvm.org/docs/SafeBuffers.html"
    },
    {
      "id": "mssdl",
      "title": "/sdl (Enable Additional Security Checks)",
      "publisher": "Microsoft Learn",
      "date": "checked 5 Nov 2026",
      "url": "https://learn.microsoft.com/en-us/cpp/build/reference/sdl-enable-additional-security-checks"
    },
    {
      "id": "gcc16",
      "title": "GCC 16 Release Series: Changes",
      "publisher": "GCC",
      "date": "16.1, 30 Apr 2026",
      "url": "https://gcc.gnu.org/gcc-16/changes.html"
    },
    {
      "id": "gccopt",
      "title": "Optimize Options",
      "publisher": "GCC manual",
      "date": "checked 5 Nov 2026",
      "url": "https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html"
    },
    {
      "id": "clang23",
      "title": "Clang 23.1.0 Release Notes",
      "publisher": "LLVM",
      "date": "checked 5 Nov 2026",
      "url": "https://releases.llvm.org/23.1.0/tools/clang/docs/ReleaseNotes.html"
    },
    {
      "id": "opensslrel",
      "title": "Release strategy",
      "publisher": "OpenSSL",
      "date": "updated 7 May 2026",
      "url": "https://openssl-library.org/policies/releasestrat/"
    },
    {
      "id": "cvebrotli",
      "title": "CVE-2026-111497 (Brotli decoder)",
      "publisher": "Google",
      "date": "22 Oct 2026",
      "url": "https://www.cve.org/CVERecord?id=CVE-2026-111497"
    },
    {
      "id": "p3471",
      "title": "P3471R4: Standard library hardening",
      "publisher": "WG21",
      "date": "14 Feb 2025",
      "url": "https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p3471r4.html"
    },
    {
      "id": "p4433",
      "title": "P4433R0: Do not remove Contracts from C++26",
      "publisher": "WG21",
      "date": "23 Oct 2026",
      "url": "https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2026/p4433r0.pdf"
    },
    {
      "id": "gcc15",
      "title": "GCC 15 Release Series: Changes",
      "publisher": "GCC",
      "date": "15.1, 25 Apr 2025",
      "url": "https://gcc.gnu.org/gcc-15/changes.html"
    },
    {
      "id": "cisaroad",
      "title": "The Case for Memory Safe Roadmaps",
      "publisher": "CISA, NSA and partners",
      "date": "Dec 2023",
      "url": "https://www.ic3.gov/CSA/2023/231206.pdf"
    },
    {
      "id": "ruleof2",
      "title": "The Rule Of 2",
      "publisher": "Chromium",
      "date": "checked 5 Nov 2026",
      "url": "https://chromium.googlesource.com/chromium/src/+/main/docs/security/rule-of-2.md"
    }
  ]
}