Project 2: Integer Overflow Detection Library
A library of safe arithmetic functions that detect and prevent integer overflow for addition, subtraction, multiplication, and division across all integer types.
Quick Reference
| Attribute | Value |
|---|---|
| Primary Language | C |
| Alternative Languages | Rust (has built-in!), C++ |
| Difficulty | Level 2: Intermediate |
| Time Estimate | 1 week |
| Knowledge Area | Secure Coding / Arithmetic Safety |
| Tooling | GCC builtins, UBSan |
| Prerequisites | Understanding of integer representation, two’s complement |
What You Will Build
A library of safe arithmetic functions that detect and prevent integer overflow for addition, subtraction, multiplication, and division across all integer types.
Why It Matters
This project builds core skills that appear repeatedly in real-world systems and tooling.
Core Challenges
- Detecting overflow before it happens → maps to pre-check patterns
- Handling signed vs unsigned → maps to different overflow behavior
- Type width differences → maps to int, long, size_t variations
- Performance considerations → maps to compiler builtins vs manual checks
Key Concepts
- Two’s Complement Arithmetic: “Computer Systems: A Programmer’s Perspective” Ch. 2
- Integer Overflow Patterns: CERT C INT32-C
- Safe Integer Libraries: SafeInt library documentation
Real-World Outcome
$ ./test_safe_math
Testing safe_add_size_t...
✓ 1000 + 2000 = 3000 (no overflow)
✓ SIZE_MAX + 1 = OVERFLOW DETECTED
✓ SIZE_MAX/2 + SIZE_MAX/2 = SIZE_MAX-1 (no overflow)
Testing safe_mul_size_t...
✓ 1000 * 1000 = 1000000 (no overflow)
✓ SIZE_MAX * 2 = OVERFLOW DETECTED
✓ 1000000000 * 5 = OVERFLOW DETECTED (on 32-bit size_t)
Testing safe_alloc_array...
✓ alloc_array(1000000, 4) detected overflow, returned NULL
✓ alloc_array(1000, 4) = 4000 bytes allocated
Testing CVE simulation...
Simulating CVE-2021-XXXX (count * element_size overflow)
✓ Vulnerable code: Allocates 64 bytes, copies 4GB!
✓ Safe code: Detects overflow, returns error
All tests passed!
Implementation Guide
- Reproduce the simplest happy-path scenario.
- Build the smallest working version of the core feature.
- Add input validation and error handling.
- Add instrumentation/logging to confirm behavior.
- Refactor into clean modules with tests.
Milestones
- Milestone 1: Minimal working program that runs end-to-end.
- Milestone 2: Correct outputs for typical inputs.
- Milestone 3: Robust handling of edge cases.
- Milestone 4: Clean structure and documented usage.
Validation Checklist
- Output matches the real-world outcome example
- Handles invalid inputs safely
- Provides clear errors and exit codes
- Repeatable results across runs
References
- Main guide:
LEARN_SECURE_C_AND_EXPLOIT_AWARENESS.md - “Secure Coding in C and C++” by Robert C. Seacord