Better memory bounds in C function signatures
Summary
In 2025 Felix von Leitner wished that the C standard would adopt a syntax that the Linux man pages now use: function parameters whose size is linked directly in the prototype to another parameter. So far there is only a GCC-specific extension via __attribute__, which clang does not support. Since von Leitner started using these attributes widely, the compiler warns when a pointer is passed with a larger length than the memory it points to.
What it is about
In C, buffers are usually passed as a pointer plus a separate length. The compiler does not know whether the two match. Many security vulnerabilities arise exactly here: a buffer is 50 bytes long, but a function writes 100 into it. A notation such as char s[maxlen] in the prototype tells the compiler that s must be at least maxlen bytes long, and it can detect incorrect calls.
The man pages’ new notation uses a forward declaration of the length parameter for this, so that the length can be used even if it comes after the buffer in the parameter list. The post refers to a proposal to the C standards committee intended to standardise exactly this.
Why it matters
Memory errors in C and C++ are responsible for a large proportion of severe security vulnerabilities. In addition to switching to memory-safe languages such as Rust, it is therefore important to make existing C code safer. Annotations that the compiler can check are an inexpensive way to do this, because they require no restructuring and make errors visible at compile time.
Ideas
- Prototypes can link a buffer’s size to a length parameter.
- The compiler can then detect wrong lengths at the call site.
- Crypto libraries would benefit particularly from such annotations.
Insights
- Many memory errors can be found at compile time through better type information.
- Compiler-specific extensions slow down the spread of good ideas.
Facts
- GCC supports such checks via __attribute__, clang does not so far.
- The Linux man pages use their own notation with a forward declaration of the length.
- The post uses the crypto library libsodium as an example.
References
Remarks
- The linked proposal is document N3394 at the C standards committee WG14.
Recommendations
- In C projects, use the available compiler annotations for buffer sizes and enable the warnings.
- For new security-critical code, check whether a memory-safe language is an option.
Found a mistake or have something to add? Get in touch.
Links to the original source and the Web Archive open in a new tab.