Terminology (4)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Undefined behavior
- An operation for which the C++ standard places no requirement on the program, such as reading past an array or overflowing a signed integer.
- As-if rule
- A compiler may transform code while preserving permitted observable behavior for defined executions.
- Dangling reference
- A reference to an object whose lifetime has ended, for example an element of a vector that has since reallocated.
- Sanitizer
- A compiler option that adds run-time checks, such as AddressSanitizer for memory errors and UBSan for undefined operations.
Where the execution contract ends
The as-if rule concerns observable behavior rather than a literal sequence of source operations. An implementation may rearrange or eliminate work when the defined program still has the behavior C++ permits. Undefined behavior is an operation for which that language contract places no requirements on execution; it does not promise a crash or a diagnostic.
This extends the optimization lesson into bounds, control flow and object lifetime. To assess a transformed program, first establish that each executed access is valid and that the objects it uses are still alive. Only then can agreement between builds support a correctness claim. Warnings and sanitizers supply evidence about particular source patterns or executed paths, rather than a proof that every path is defined.
01The as-if rule
What may an optimizer assume?
The station’s fare gate passes a debug check, then blocks cards that are not on its hotlist. Its scan reads beyond an array. C++23 places no requirements on an execution with undefined behavior, so a reassuring result from one build cannot establish that the gate is correct.
C++ describes an abstract machine. A compiler can reorder, remove and rewrite code while preserving permitted observable behavior for defined executions. Undefined behavior supplies no such requirements, which lets an optimizer eliminate paths that would require it.
Optimization, AOT, and JIT showed the simplest case: x + 1 > x becomes true because signed overflow is undefined. The same reasoning applies to array bounds. In this station gate, the back office pushes a hotlist of four cards reported lost or stolen. The loop that checks it should stop at index 3 but also reads hotlist[4], one past the end.
#include <cstddef>
#include <cstdio>
#include <initializer_list>
const int hotlist[4] = {1013, 1021, 1034, 1055}; // cards reported lost or stolen
bool blocked_debug(int card) {
for (std::size_t i = 0; i <= 4; ++i) // reads hotlist[4], one past the end
if (hotlist[i] == card)
return true;
return false;
}
[[gnu::optimize("O2")]] bool blocked_release(int card) {
for (std::size_t i = 0; i <= 4; ++i)
if (hotlist[i] == card)
return true;
return false;
}
int main() {
for (int card : {1021, 1007}) {
std::printf("card %d: debug build %s, release build %s\n", card,
blocked_debug(card) ? "blocked" : "allowed",
blocked_release(card) ? "blocked" : "allowed");
}
}
g++ -std=c++23 -Wall -Wextra main.cpp -o main && ./main
The retained results come from GCC 12.2 on arm64. The first two probes compare an ordinary function in a default -O0 build with a function marked [[gnu::optimize("O2")]] in the same binary. This GCC-specific per-function setting is not a complete release configuration; other compilers may diagnose or ignore the attribute. The third probe uses an ordinary default build. Predict the recorded results, then check each source defect; the undefined operations have no portable output.
02Missing returns
What does a function return when it returns nothing?
Normal flow reaching the end of this ordinary int function is undefined. It must return a result on a normally completing path; throwing or never returning is different. The special end-of-main rule does not apply to fare.
The gate’s fare table, in cents, sells adult and child tickets. The back office has started issuing senior concession cards, but the table has no return for them yet.
#include <cstdio>
#include <string>
// Fares in cents.
int fare_debug(const std::string &kind) {
if (kind == "adult")
return 290;
if (kind == "child")
return 145;
} // no return for any other kind
[[gnu::optimize("O2")]] int fare_release(const std::string &kind) {
if (kind == "adult")
return 290;
if (kind == "child")
return 145;
}
int main() {
for (const char *kind : {"adult", "child", "senior"})
std::printf("%s: debug build %d, release build %d\n", kind, fare_debug(kind),
fare_release(kind));
}
03Lifetimes
Is a reference to an element still valid after the vector grows?
Some undefined behavior appears without any optimization. A reference, pointer or iterator into a std::vector refers to the current storage. When push_back needs more capacity, the vector allocates a new array, moves the elements and frees the old one.
A card holder can pay for companions travelling with them. The gate prints each companion a paper ticket from its own number sequence and adds a rider for it, while the program keeps a reference to the payer.
#include <cstdio>
#include <vector>
struct Rider {
int id; // card number, or companion ticket number
int trips;
};
int main() {
std::vector<Rider> riders{{1007, 1}};
Rider &payer = riders[0];
int next_ticket = 5001;
std::printf("capacity before: %zu\n", riders.capacity());
for (int companion = 1; companion <= 3; ++companion) {
riders.push_back({next_ticket++, 1}); // may move every rider to a new array
payer.trips += 1;
}
std::printf("capacity after: %zu\n", riders.capacity());
std::printf("rider 1007: %d trips (3 companions paid for)\n", riders[0].trips);
}
04Practice
Fix the station fare gate
Fare settlement uses the gate’s trip report. Repair the scan first, then its unsupported-fare result, then the payer accounting while paper-ticket riders are added. The supplied callers and earlier repairs remain in place. The O2 attribute controls selected GCC functions; compare repaired defined behavior with the public expected output rather than treating starter UB results as guarantees.
The station fare gate
Stay inside the hotlist, return a fare on every path, then keep the payer valid while companions are added.
In the frontend A WebAssembly view retained across growth Optional
A fare display keeps a byte view of a WebAssembly memory while a new batch grows that memory. Inspect this diagnostic before trusting the old view.
Each call creates fresh ordinary unshared memory with the default fixed-length buffer. Assume growth succeeds; no resizable-buffer conversion or WebAssembly module is involved. What are oldLength and first?
export function staleView() {
const memory = new WebAssembly.Memory({ initial: 1, maximum: 2 });
const oldView = new Uint8Array(memory.buffer);
oldView[0] = 7;
memory.grow(1);
return { oldLength: oldView.length, first: oldView[0] };
} Growth detaches the old fixed-length buffer: oldLength is 0 and first is undefined. These are defined JavaScript results. C++ invalid-reference accesses provide no corresponding result guarantee.
Sources: WebAssembly JavaScript interface: Memory,ECMAScript: TypedArray exotic objects.
Sources
Sign in to keep your read marks on every device. Sign in
Was this helpful?