Skip to content
Language guides Reviewed 2026-09-12

C and C++ secure coding

C and C++ require deliberate bounds, lifetime and arithmetic checks at input boundaries. This guide uses C++17 standard containers and a small C formatting example. It covers targeted fixes, not whole-program memory safety or every way undefined behavior can arise.

Check the index before access

Assume values is a std::vector<int> and index is a parsed std::size_t. The function returns the selected integer.

Unsafe when the index is untrusted: unchecked access.

return values[index];

Safer: reject an index outside the valid range.

if (index >= values.size()) {
    throw std::out_of_range("Invalid index");
}
return values[index];

Include <vector> and <stdexcept> in the surrounding program. Convert the exception into a controlled application error at the request boundary. An alternative is values.at(index) with equivalent error handling. Validate a signed input before converting it to an unsigned size type. The C++ Core Guidelines on bounds explain the broader concern.

Keep format strings constant

For a non-null, terminated C string message, these calls are alternatives:

/* Unsafe: message controls the format. */
printf(message);
/* Safer: message is a string argument. */
printf("%s", message);

The fixed format prevents percent characters in the message from selecting format operations. It does not prove the pointer is valid or remove sensitive data from output. CERT's input/output rules include this format-string boundary.

Check the fixes

For the safer bounds implementation, test an empty vector, index zero, the last valid index and an index equal to the vector size. The invalid cases should fail predictably without reading memory outside the container. Test only the safer formatting call with Demo %s label and verify literal output.

Review buffer allocation, format strings, command injection and path traversal. Combine source review with compiler warnings, sanitizer-enabled test builds and realistic input limits. Scanner findings depend on the analyzed files and enabled rules; a clean scan is not a certification that memory errors cannot occur.