llvm / llvm-project

The LLVM Project is a collection of modular and reusable compiler and toolchain technologies.
http://llvm.org
Other
28.87k stars 11.92k forks source link

-Wformat-truncation warning size does not agree with the return value from snprintf #71320

Open andrew-aitchison opened 1 year ago

andrew-aitchison commented 1 year ago

clang++-18 (version 18.0.0 (++20231104083419+83888a5404d4-1~exp1~20231104083522.106) reports

format-trunc.cpp:9:12: warning: 'snprintf' will always be truncated; specified size is 16, but format string expands to at least 17 [-Wformat-truncation]
    9 |         int ret = snprintf(szString,
      |                   ^
1 warning generated.

for the following code, but when run it prints:

snprintf(*, 16, fmt, ...) returns 15

which suggests that at least for this value the format string does fit in the given space.

#include <stdio.h>

int main(int argc, char*argv[])
{
    const double d = .123456789012345;

    char szString[15 + 1];
    int ret = snprintf(szString,
                       sizeof(szString),
                       "%#+015.10f", d);

    printf("snprintf(*, %zu, fmt, ...) returns %d\n",
           sizeof(szString),
           ret);

    return 0;
}
andrew-aitchison commented 1 year ago

Originally reported against gdal where the issue was first seen: https://github.com/OSGeo/gdal/issues/8664