https://gcc.gnu.org/bugzilla/show_bug.cgi?id=117369
Bug ID: 117369 Summary: False positive Wanalyzer-out-of-bounds fanalyzer warnings for sprintf to offset at -O1 and above Product: gcc Version: 14.2.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: analyzer Assignee: dmalcolm at gcc dot gnu.org Reporter: zany at triq dot net Target Milestone: --- With gcc (Debian 14.2.0-6) 14.2.0 on Linux 6.11.4-cloud-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.11.4-1 (2024-10-20) x86_64 GNU/Linux using GCC from https://packages.debian.org/trixie/gcc-14 as installed in https://cloud.debian.org/images/cloud/trixie/daily/20241028-1914/debian-13-genericcloud-amd64-daily-20241028-1914.json with additional $ sudo apt-get install build-essential for this program with relevant #include <stdio.h> expanded for brevity: extern int sprintf (char *__restrict __s, const char *__restrict __format, ...) __attribute__ ((__nothrow__)); int main() { char buf[16]; sprintf(buf + 1, "."); } gcc -O1 -fanalyzer -c test.c (also -Os, -O2, -O3, but -O0 does not report this) We get a false positive -Wanalyzer-out-of-bounds warning: test.c: In function ‘main’: test.c:5:5: warning: stack-based buffer overflow [CWE-121] [-Wanalyzer-out-of-bounds] 5 | sprintf(buf + 1, "."); | ^~~~~~~~~~~~~~~~~~~~~ ‘main’: events 1-2 | | 4 | char buf[16]; | | ^~~ | | | | | (1) capacity: 16 bytes | 5 | sprintf(buf + 1, "."); | | ~~~~~~~~~~~~~~~~~~~~~ | | | | | (2) out-of-bounds write at byte 16 but ‘buf’ ends at byte 16 | test.c:5:5: note: write of 1 byte to beyond the end of ‘buf’ 5 | sprintf(buf + 1, "."); | ^~~~~~~~~~~~~~~~~~~~~ test.c:5:5: note: valid subscripts for ‘buf’ are ‘[0]’ to ‘[15]’ ┌──────────────────────────────────────────────────────────────┐ │ write of ‘char[16]’ (16 bytes) │ └──────────────────────────────────────────────────────────────┘ │ │ │ │ │ │ v v v ┌───┬───┬────────────────────────────┬─────────┐ ┌─────────────────┐ │[0]│...│ [1] │ [15] │ │ │ ├───┴───┴────────────────────────────┴─────────┤ │after valid range│ │ ‘buf’ (type: ‘char[16]’) │ │ │ └──────────────────────────────────────────────┘ └─────────────────┘ ├──────────────────────┬───────────────────────┤ ├────────┬────────┤ │ │ ╭─────────┴────────╮ ╭──────────┴──────────╮ │capacity: 16 bytes│ │⚠️ overflow of 1 byte│ ╰──────────────────╯ ╰─────────────────────╯