llvm-project/clang/docs/analyzer/checkers/storetoimmutable_example.cpp
Endre Fülöp a3d0c541eb
[clang][analyzer] Add StoreToImmutable checker (#150417)
This adds alpha.core.StoreToImmutable, a new alpha checker that detects
writes
to immutable memory regions, implementing part of SEI CERT Rule ENV30-C.
The
original proposal only handled global const variables, but this
implementation
extends it to also detect writes to:
- Local const variables
- String literals
- Const parameters and struct members
- Const arrays and pointers to const data

This checker is the continuation of the work started by zukatsinadze.
Discussion: https://reviews.llvm.org/D124244
2025-08-04 14:56:33 +02:00

22 lines
653 B
C++

const int global_const = 42;
struct TestStruct {
const int x;
int y;
};
void immutable_violation_examples() {
*(int *)&global_const = 100; // warn: Trying to write to immutable memory
const int local_const = 42;
*(int *)&local_const = 43; // warn: Trying to write to immutable memory
// NOTE: The following is reported in C++, but not in C, as the analyzer
// treats string literals as non-const char arrays in C mode.
char *ptr_to_str_literal = (char *)"hello";
ptr_to_str_literal[0] = 'H'; // warn: Trying to write to immutable memory
TestStruct s = {1, 2};
*(int *)&s.x = 10; // warn: Trying to write to immutable memory
}