Table of Contents
A buffer overflow occurs when a program writes beyond the storage reserved for a buffer. The write can corrupt neighboring data or crash the program. When the vulnerable code handles untrusted input, the bug can become a security issue.

Stack and heap buffer overflows
- Stack-based overflow: The out-of-bounds write affects a buffer allocated in a function's stack storage. This differs from stack exhaustion caused by excessive recursion.
- Heap-based overflow: The write exceeds the bounds of dynamically allocated storage. It can corrupt adjacent objects or data used by the runtime.
A size calculation error can cause either type. For example, a byte buffer allocated from a character count may be too small after an encoding conversion. Integer overflow during allocation and forgetting a C string's terminating byte are other causes. Read the C arrays, strings, and pointers lesson for the language basics.
Prevent out-of-bounds writes
- Carry the buffer capacity alongside its data. Check the length and any offset in the same units, such as bytes, before writing. Include space for terminators where required.
- Check arithmetic before allocating from counts or lengths, and account for expansions produced by encoders and formatters.
- Use APIs that accept a capacity and check their return values. Prefer memory-safe languages or bounds-checked abstractions for new components where practical.
- Run tests on instrumented builds with tools such as AddressSanitizer. Cover empty, exact-fit, and too-long input, and verify that invalid sizes leave state unchanged.
Production protections such as stack guards and address randomization can reduce the impact of some errors. Fix the faulty write itself. See MITRE's out-of-bounds write reference and the TipsMake C learning roadmap for related material.
Reader Comments 0
Sign in with email or Google to join the discussion.