GCC Newspaper
NOVEMBER 30, 2026
Date
/
Architectures
Components
Topics
News & Policy
Other
gcc/tree-optimization

Fix strnlen optimization to avoid incorrect full string length recording.

Corrects `strlen` optimization to only record full string length for `strlen`, not `strnlen`, preventing incorrect length assumptions.

This commit fixes a bug in GCC’s string length optimization where strnlen was incorrectly recorded as the full string length. The handle_builtin_strlen function now correctly distinguishes between strlen and strnlen, ensuring that the full length is only recorded for strlen. This prevents subsequent optimizations from using a potentially shorter strnlen bound as the definitive string length, thus avoiding incorrect program behavior.

In Details

The tree-ssa-strlen.cc pass, specifically the handle_builtin_strlen function, previously recorded the result of strnlen as the full string length if the strinfo only had a lower bound. This commit corrects that by only recording the full length for strlen itself, aligning with the behavior established for PR86204. This prevents strnlen's bound from being prematurely treated as the absolute string length, which could lead to incorrect subsequent analyses.

For Context
strnlen
A C standard library function that computes the length of a string, but stops after a specified maximum number of characters have been examined. It returns the minimum of the actual string length and the specified bound.
strlen
A C standard library function that computes the length of a null-terminated string.
strinfo
A data structure used in GCC's tree optimization passes to store information about string properties, such as its length or whether it's null-terminated.
tree-ssa-strlen.cc
The GCC source file containing the implementation for the SSA-based string length optimization pass.
Filed Under: gccoptimizationstring handling