Files
tai/research/safe-cpp-practices/integer-overflow-size-checks.md
T

51 lines
2.0 KiB
Markdown
Raw Normal View History

# Integer overflow and allocation-size checks in C/C++
## Metadata
| Field | Value |
|---|---|
| Institute | Molodetz Institute — Research & Retrieval Division |
| Subject | safe-cpp-practices |
| Document type | Source Dossier |
| Tier | 1 |
| Source title | Integer overflow and allocation-size checks in C/C++ |
| Source URL | https://offlinemark.com/int-overflow/ |
| Source publisher / author | offlinemark; Offensive360; Orbis AppSec |
| Source type | blog post |
| Source date (published) | Unknown — not stated |
| Date researched | 2026-10-27 |
| Researched by | tai (agent), model: Claude Opus 4.8, on behalf of retoor |
| Research method | web search synthesis |
| Confidence | High |
| Status | Active |
## Summary
The canonical guidance for size arithmetic on untrusted input: check before the operation, never after, and never let a parsed count drive allocation or pointer math before its range and an application limit are both checked.
## Key findings
- Addition overflow guard for size_t: test `a > SIZE_MAX - b` before computing `a + b` (exactly the `len > size - pos` form detz now uses).
- Multiplication guard: `b != 0 && a > SIZE_MAX / b`.
- Checking a signed result after the fact is too late: the overflow was already undefined behavior.
- A negative value converted to an unsigned size becomes huge; validate parsed numbers before the conversion.
- Keep the validated count next to the allocation so the allocation and the loop cannot use different counts.
## Pros / strengths
Precise, copy-pasteable guards; names the signed->unsigned trap that caused the crash.
## Cons / limitations / caveats
Blog-level sourcing, not a standard; no single authoritative citation.
## Relevance to tai
This is the root-cause cure. detz replaced every `pos + len > size` with `len > size - pos`, reads lengths unsigned, and range-checks before slicing or allocating.
## Changelog
| Date | Change |
|---|---|
| 2026-10-27 | Initial dossier created (web search synthesis). |