CertC-MSC15

Do not depend on undefined behavior

Required inputs: IR, StaticSemanticAnalysis

The C Standard, subclause 3.5.3 [ ISO/IEC 9899:2024 ], defines undefined behavior as

behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this document imposes no requirements

Subclause 4 explains how the standard identifies undefined behavior (see also undefined behavior 1 of Annex J).

If a "shall" or "shall not" requirement that appears outside of a constraint or runtime-constraint is violated, the behavior is undefined. Undefined behavior is otherwise indicated in this document by the words "undefined behavior" or by the omission of any explicit definition of behavior. There is no difference in emphasis among these three; they all describe "behavior that is undefined".

Annex J, subclause J.2, "Undefined behavior," enumerates the circumstances under which the behavior of a program is undefined. This list is duplicated on the CC. Undefined Behavior page.

Behavior can be classified as undefined by the C standards committee for the following reasons:

  • To give the implementor license not to catch certain program errors that are difficult to diagnose

  • To avoid defining obscure corner cases that would favor one implementation strategy over another

  • To identify areas of possible conforming language extension: the implementor may augment the language by providing a definition of the officially undefined behavior

Conforming implementations can deal with undefined behavior in a variety of fashions, such as ignoring the situation completely, with unpredictable results; translating or executing the program in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message); or terminating a translation or execution (with the issuance of a diagnostic message). Because compilers are not obligated to generate code for undefined behavior, these behaviors are candidates for optimization. By assuming that undefined behaviors will not occur, compilers can generate code with better performance characteristics.

Increasingly, compiler writers are taking advantage of undefined behaviors in the C programming languages to improve optimizations. These optimizations frequently interfere with the ability of developers to perform cause-effect analysis on their source code—that is, to analyze the dependence of downstream results on prior results. Consequently, these optimizations are eliminating causality in software and are increasing the probability of software faults, defects, and vulnerabilities .

All of this puts the onus on the programmer to develop code that is free from undefined behaviors, with or without the help of the compiler.

Noncompliant Code Example

An example of undefined behavior in C is the behavior on signed integer overflow (see also INT32-C. Ensure that operations on signed integers do not result in overflow ). This noncompliant code example depends on this behavior to catch the overflow:

#include <assert.h>
#include <limits.h>
#include <stdio.h>

int foo(int a) {
  assert(a + 100 > a);
  printf("%d %d\n", a + 100, a);
  return a;
}

int main(void) {
  foo(100);
  foo(INT_MAX);
  return 0;
}

This code checks for signed integer overflow by testing whether a + 100 > a . This test cannot evaluate to false unless an integer overflow occurs. However, because a conforming implementation is not required to generate code for undefined behavior, and signed integer overflow is undefined behavior, this code may be compiled out. For example, GCC 4.1.1 optimizes out the assertion for all optimization levels, and GCC 4.2.3 optimizes out the assertion for programs compiled with -O2 -level optimization and higher.

On some platforms, the integer overflow causes the program to terminate (before it has an opportunity to test).

Compliant Solution

This compliant solution does not depend on undefined behavior:

#include <assert.h>
#include <limits.h>
#include <stdio.h>

int foo(int a) {
  assert(a < (INT_MAX - 100));
  printf("%d %d\n", a + 100, a);
  return a;
}

int main(void) {
  foo(100);
  foo(INT_MAX);
  return 0;
}
Risk Assessment

Although it is rare that the entire application can be strictly conforming , the goal should be that almost all the code is allowed for a strictly conforming program (which among other things means that it avoids undefined behavior ), with the implementation-dependent parts confined to modules that the programmer knows are needed to adapt to the platform when it changes.

Recommendation Severity Likelihood Detectable Repairable Priority Level
MSC15-C High Likely No No P9 L2
Related Guidelines
SEI CERT C++ Coding Standard VOID MSC15-CPP. Do not depend on undefined behavior
ISO/IEC TR 24772 Unspecified Behaviour [BQF]
Undefined Behaviour [EWF]
Implementation-Defined Behaviour [FAB]
Bibliography
[ ISO/IEC 9899:2024 ] Subclause 3.5.3, "Undefined Behavior"
Subclause 4, "Conformance"
Subclause J.2, "Undefined Behavior"
[ Seacord 2013 ] Chapter 5, "Integer Security"
Excerpt from SEI CERT C Coding Standard: Rules for Developing Safe, Reliable, and Secure Systems (2016 Edition) and SEI CERT C Coding Standard [https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/recommendations/miscellaneous-msc/msc15-c], Copyright (C) 1995-2026 Carnegie Mellon University. See 9.4 3rd-Party Licenses in the documentation for full details.

Possible Messages

Key

Text

Severity

Disabled

arithmetic_out_of_bounds

Pointer arithmetic on {node0} might create pointer outside array bounds of {name0}

None

False

assigned_to_pointer_to_const

Assigning the address of a partially initialized variable to some pointer-to-const

None

False

certain_shift_amount_negative

Shift by a negative bit count (undefined behavior)

None

False

certain_shift_amount_too_large

Shift by the integer width or more (undefined behavior)

None

False

certain_shift_right_negative

Right shift with negative left-hand-side

None

False

division_by_zero

Division by zero

None

False

double_free

Dynamic memory released here was already released earlier

None

False

float_division_by_zero

Floating point division by floating point zero

None

False

modulo_by_zero

Modulo by zero

None

False

null_deref

Pointer is NULL at dereference

None

False

null_this_arg

Pointer passed in as argument for this is NULL

None

False

out_of_bounds

Access into array is out of bounds

None

False

pass_as_pointer_to_const_param

Passing uninitialized variable by pointer as function parameter with pointer-to-const type

None

False

possible_division_by_zero

Possible division by zero

None

False

possible_double_free

Dynamic memory released here possibly already released earlier

None

False

possible_float_division_by_zero

Possible floating point division by zero

None

False

possible_indirect_out_of_bounds

Pointer-indirect access through {node0} might be out of bounds accessing {name0}

None

False

possible_modulo_by_zero

Possible modulo by zero

None

False

possible_null_deref

Pointer may be NULL at dereference

None

False

possible_null_deref_improbable

Pointer may be NULL at dereference (improbable)

None

False

possible_null_this_arg

Pointer passed in as argument for this may be NULL

None

False

possible_out_of_bounds

Access into array might be out of bounds

None

False

possible_return_value_uninit

Function return value is potentially not initialized

None

False

possible_stack_free

{name0} possibly released by call to {node0} is a stack or static object

None

False

possible_uninit

Use of possibly uninitialized variable

None

False

possible_unrelated_ptr_comparison

Comparing possibly unrelated pointers

None

False

possible_unrelated_ptr_subtraction

Subtracting possibly unrelated pointers

None

False

possible_use_after_free

Dynamic memory possibly used after it was previously released

None

False

possible_wrong_release

Resource possibly released using wrong function (allocation used {node0})

None

False

possibly_initialized

Use of possibly uninitialized variable (previous call {node0} might have initialized the variable)

None

False

return_value_uninit

Function return value is not initialized

None

False

shift_amount_negative

Possible shift by a negative bit count (undefined behavior)

None

False

shift_amount_too_large

Possible shift by the integer width or more (undefined behavior)

None

False

shift_right_negative

Possible right shift with negative left-hand-side

None

False

signed_overflow_negative

Arithmetic computation may cause negative overflow

None

False

signed_overflow_positive

Arithmetic computation may cause positive overflow

None

False

stack_free

{name0} released by call to {node0} is a stack or static object

None

False

static_signed_overflow_negative

Arithmetic computation may cause negative overflow

None

False

static_signed_overflow_positive

Arithmetic computation may cause positive overflow

None

False

static_unsigned_wraparound_negative

Arithmetic computation may cause negative wrap-around

None

False

static_unsigned_wraparound_positive

Arithmetic computation may cause positive wrap-around

None

False

undefined_behaviour

Undefined behaviour: {}

None

False

undereferenced_arithmetic_out_of_bounds

Pointer arithmetic on {node0} might create pointer one past the end of {name0} (but not dereferenced)

None

False

undereferenced_out_of_bounds

Access is one past the end of the array (but not dereferenced)

None

False

undereferenced_possible_indirect_out_of_bounds

Pointer-indirect access through {node0} might be one past the end accessing {name0} (but not dereferenced)

None

False

undereferenced_possible_out_of_bounds

Access might be one past the end of the array (but not dereferenced)

None

False

uninit

Use of uninitialized variable

None

False

unrelated_ptr_comparison

Comparing unrelated pointers

None

False

unrelated_ptr_subtraction

Subtracting unrelated pointers

None

False

use_after_free

Dynamic memory used after it was previously released

None

False

wrong_release

Resource released using wrong function (allocation used {node0})

None

False

Options

abstract_interpretation_div_by_zero

abstract_interpretation_div_by_zero : bool = True

Use additional "symbolic expression analysis" as postprocessing step. This can remove false positives, but might require more time. Option is automatically active if StaticSemanticAnalysis/performance.general.enhanced_analysis is active.
 

abstract_interpretation_maximal_tracked_array_index

abstract_interpretation_maximal_tracked_array_index : int = 10

The number of explicit indices in array expressions per routine tracked by the "symbolic expression analysis". For example, consider the following program.

extern signed char a[6];
int main()
{
    if (a[2] < 0)
    {
        a[2]++;
    }
    if (a[3] < 0)
    {
        a[3]++;
    }
    if (a[4] < 0)
    {
        a[4]++;
    }
    return 0;
}

If the value of this option is set to 2, the first two array index expressions encountered in the routine are tracked. Hence, the analysis can use the facts a[2] < 0 and a[3] < 0 to infer that a[2]++ and a[3]++ do not overflow, but it will not track the third array access in this routine.

A higher value of the option can cause more consumption of memory and time for the analysis.

 

abstract_interpretation_out_of_bounds

abstract_interpretation_out_of_bounds : bool = False

Use additional "symbolic expression analysis" as postprocessing step. This can remove false positives, but might require more time. Option is automatically active if option StaticSemanticAnalysis/performance.general.enhanced_analysis is active.
 

abstract_interpretation_overflow

abstract_interpretation_overflow : bool = False

Use abstract-interpretation-based "symbolic expression analysis" as additional postprocessing step.
 

abstract_interpretation_overflow_unrolling_level

abstract_interpretation_overflow_unrolling_level : int = 0

How many levels of conditions are traversed to compute additional constraints for the "symbolic expression analysis".
 

additional_local_array_check

additional_local_array_check : bool = True

Invoke an additional analysis that tries to remove false positives involving accesses to local array variables and in particular their initialization. The analysis attempts to report only the first use of an uninitialized value. Consider e.g. the following example:
    int example()
    {
        int a[10];
        int b[20];
        int uninit_var;
        for (int i = 0; i < 10; ++i)
        {
L1:         a[i] = uninit_var; // use of uninit_var reported
            b[i] = i;
        }
        int result = a[3]; // not reported, since already reported at L1
        result += b[15]; // reported; c[] is not (completely) initialized
        return result;
    }
    
 

assume_globals_are_initialized

assume_globals_are_initialized : bool = True

Whether global and local static variables should be treated as initialized (as specified by the language).
 

check_array_access_with_unknown_index

check_array_access_with_unknown_index : bool = False

Whether array accesses like a[i] with non-literal index i should be checked as well.
 

check_non_array_pointers

check_non_array_pointers : bool = False

Whether the check should also consider pointers to non-arrays (e.g., comparison of pointers to different fields). If enabled, a pointer to an object that is not an array is treated as if it were a pointer to the first element of an array with a single element.
 

check_signed

check_signed : bool = True

Whether issues for signed integer operations should be reported. For casts including implicit conversions, the target type of the cast is used.
 

check_unsigned

check_unsigned : bool = True

Whether wrap-around for unsigned integer operations should be reported. For casts including implicit conversions, the target type of the cast is used.
 

compiler_messages_on_undefined

compiler_messages_on_undefined

Type: set[int]

Default: {1, 1037, 120, 1282, 137, 138, 157, 1665, 167, 171, 172, 1816, 1817, 1818, 192, 2, 28, 2903, 31, 40, 549, 57, 59, 7, 70, 8, 968}

Compiler messages of these types are reported.
 

exclude_from_pointer_to_const_param_check

exclude_from_pointer_to_const_param_check : set[bauhaus.analysis.config.QualifiedName] = {'__builtin_object_size'}

Names of routines whose parameters should be excluded from the check for passing uninitialized variables by pointer as parameter with pointer-to-const type.
 

exclude_very_high_indices

exclude_very_high_indices : bool = True

Enables heuristic to detect false positives: When index used for array access is very high in comparison to the array's size, assume false positive.
 

execute_checks_covered_in_other_rules

execute_checks_covered_in_other_rules : bool = False

Whether checks covered by other, dedicated CERT rules (CertC-ARR36, CertC-EXP33, CertC-ARR30, CertC-INT30/INT31/INT32, CertC-INT33, CertC-WIN30, CertC-MEM30/FIO46, CertC-EXP34, CertC-MEM34) should be executed here as well.
 

filter_multiple_instances

filter_multiple_instances : bool = False

Whether a null pointer dereferenced multiple times in the same function should be reported only once.
 

functions_with_ignored_deallocators

functions_with_ignored_deallocators : set[str] = set()

Set of functions (given by their qualified name) where all deallocators are ignored. For these functions, the check will never report a use-after-free. It will also assume that these functions never create freed pointers, neither by return value, out param, nor by modifying global state.
 

maximum_number_of_threads

maximum_number_of_threads : int = 0

This option determines how many threads are used during computation of this rule at most. With 0, the maximum number of threads is automatically determined with a heuristic that considers the number of available CPU cores as well as the available memory.
 

relevant_expressions

relevant_expressions

Type: RelevantExpressions

Default: 'const_and_compile_time_constant'

Which (const / constant) expressions should be considered.

Note: this is only relevant for the purely static parts of the analysis. The StaticSemanticAnalysis-based checks for runtime errors will be performed independently.

 

report_empty_points_to_sets

report_empty_points_to_sets : bool = False

Report cases where one of the pointers involved in the comparison does not point to any value. This can occur e.g. if parameters of entry functions are analyzed, for which no values are known.
 

report_freed_this_at_call

report_freed_this_at_call : bool = False

This option controls findings when a freed pointer is used in C++ to call a non-static member function. When set to true, the use at the call is directly reported. When false, the analysis waits for an actual dereference (of the this-pointer then) inside the callee, and only reports those.
 

report_null_this

report_null_this : bool = False

Whether a null pointer as argument for the this-parameter should be reported in non-virtual calls as well.
 

report_read_pointer_args_in_calls_to_undefined

report_read_pointer_args_in_calls_to_undefined : bool = True

Report when freed pointers are passed to undefined (external) functions.
 

report_unbounded_arrays

report_unbounded_arrays : bool = False

If true, accesses into arrays with unknown bound are reported as being potentially outside the allowed range. This affects arrays like extern char buf[];.
 

report_undereferenced_one_past_the_end

report_undereferenced_one_past_the_end : bool = False

If true, report accesses one past the end of an array even if there is no dereference of the resulting pointer.
 

report_unknown_index

report_unknown_index : bool = False

If false, do not report possible out-of-bound findings for which the analysis was not able to infer any restricting information about the array index (this can lead to excluding both false positives and true findings).
 

resources

resources

Type: set[str]

Default: {'C++ArrayHeapMemory', 'C++HeapMemory', 'CudaAsyncMemory', 'CudaDeviceMemory', 'CudaDriverAsyncMemory', 'CudaHostMemory', 'CudaManagedMemory', 'FileHandle', 'HeapMemory', 'UniquePtrHeapMemory'}

Set of resources to be checked (selection of rules in the Resources group).
 

suppress_well_defined_findings

suppress_well_defined_findings

Type: SuppressionMode

Default: 'NONE'

Some overflows have well-defined semantics in all C/C++ standard versions. The typical example is UINT_MAX+1 which is well-defined as 0 via wraparound. This differs from INT_MAX+1 which is either undefined or implementation-defined depending on the considered standard version. Most CPUs will compute INT_MIN but this wraparound is not guaranteed by any C/C++ standard.

Both cases are overflows and are reported by this rule. However, one might want to suppress messages for the well-defined cases. To suppress these activate this option.

Different C and C++ standard versions differ in what is well-defined, implementation-defined, or undefined. Luckily, if we only consider well-defined and do not discern between implementation-defined and undefined, we end up with only two groups: pre-C++20 and since-C++20.

 

track_conditional_initialization

track_conditional_initialization : bool = True

Whether higher precision should be used to eliminate cases where the initialization and the access are controlled by conditions in a way that the variable access is only executed when the initialization was executed. Requires more memory and runtime but can eliminate some false positives.
 

undefined_in_languages

undefined_in_languages

Type: dict[int, set[bauhaus.ir.Language_Type | bauhaus.ir.Language_Dialect_Type]]

Default:

{
   1: {'C', 'CPP98'},
   2: {'C', 'CPP98'}
}
Restricts entries of :attr:`compiler_messages_on_undefined` to the languages and language dialects in which they really are undefined behaviour. A message is reported for a file only if that file was compiled as one of the languages or dialects listed for it. Messages without an entry here are reported regardless of the language.
 

use_semantic_analysis

use_semantic_analysis : bool = True

When enabled, use semantic analysis. Otherwise filter uninitialized variable messages from the compiler.
 

witness_paths

witness_paths : bool = True

Whether witness paths should be determined and included in the issue.
 

writing_into_pointer_to_const

writing_into_pointer_to_const

Type: dict[bauhaus.analysis.config.QualifiedName, int]

Default:

{
   'cudaMemcpyToSymbol': 0
}
Names of routines (mapping to parameter index, starting at 0) having a parameter declared as pointer-to-const yet they are still writing into the pointee.
 

Option Types

These types are used by options listed above:

Language_Dialect_Type

  • C90

  • C99

  • C11

  • C18

  • C23

  • EMBEDDED_C

  • CPP98

  • CPP11

  • CPP14

  • CPP17

  • CPP20

  • CPP23

  • CPP26

  • EMBEDDED_CPP

  • ASM

  • CPP_CLI

  • CPP_CX

Language_Type

  • C

  • CPLUSPLUS

  • CPP_CLI

  • CPP_CX

  • CSHARP

  • CUDA

  • PYTHON

  • JAVA

  • ASM

  • QML

  • RUST

  • RESPONSE_FILE

  • IGNORE_FILE

  • UNKNOWN

  • AUTO

RelevantExpressions

none

No (additional) checks for overflows in const-expressions or compile time constant expressions.

const_expressions_only

Whether the analysis should statically check const-expressions (i.e., const variables and literals) that might have been reduced to a literal during compilation.

const_and_compile_time_constant

Whether the analysis should statically check const-expressions (i.e., const variables and literals) as well as compile-time constant expressions (i.e., preprocessor defines, constexprs or literals) that might have been reduced to a literal during compilation.

SuppressionMode

NONE

Suppress nothing.

PRE_CPP2020

Suppress findings that are well-defined before C++20. These are:

  • Positive and negative wrap-arounds of unsigned integers during addition, subtraction, and multiplication
  • Conversions from unsigned to unsigned integers
  • Wrap-around caused by left-shifting of unsigned integer

CPP2020

Suppress findings that are well-defined since C++20. These are:

  • Positive and negative wrap-arounds of unsigned integers during addition, subtraction, and multiplication
  • Conversions between signed and unsigned integers
  • Wrap-around caused by left-shifting
  • Shifting negative integers

Surprising mechanics of C++20 signed narrow integers

Since C++20, casts between signed and unsigned are defined as two-complement wrap-around. Overflows of signed integers are still undefined behavior and are reported by this rule. But, due to integer promotion rules, certain expressions are computed using wider integer types, which can lead to the false impression that this is no longer the case, because no overflow findings are reported there.

Suppose, that the code is compiled on a platform where short is smaller than or equal to half the size of an int. Very commonly the sizes are 2 and 4. This assumption is thus true for many platforms.

In this case, narrow signed integer types such as short or signed char are first implicitly promoted to int before the arithmetic operation is executed. Because of this promotion, the actual operation does not overflow and is thus well-defined. After the operation, an implicit cast is performed to the narrower type. This cast is well-defined in C++20 as wrapping around.

Consider the following snippet:

    static_assert(sizeof(short) == 2);
    static_assert(sizeof(int) == 4);
    short a = 0x1000;
    short b = 0x1001;
    short c = a*b;
C++20 defines c as 0x1000. The reason is that a*b is implicitly promoted to static_cast<int> (a)*static_cast<int>(b). After the promotion, the multiplication does not overflow and yields a well-defined 0x1001000. This number is then implicitly cast to 0x1000 which is also a well-defined operation.

An analogous effect can be observed for signed short addition and multiplication. Another effect is that it is well-defined to shift by up to as many bits as int has even if the shifted integer has fewer bits.

DERIVE_FROM_IR

Derive the language version from the IR compilation flags and suppress findings accordingly.