[clang] [-Wunsafe-buffer-usage] Warning Libc functions (PR #101583)
Mikael Holmén via cfe-commits
cfe-commits at lists.llvm.org
Mon Sep 9 00:42:59 PDT 2024
mikaelholmen wrote:
> > Btw a question about the new warning: So with -Wunsafe-buffer-usage-in-libc-call clang now warns on the following?
> > ```
> > #include <stdio.h>
> >
> > void foo(void) {
> > char q[10];
> > snprintf(q, 10, "%s", "hello");
> > }
> > ```
> >
> >
> >
> >
> >
> >
> >
> >
> >
> >
> >
> > It says
> > ```
> > foo.c:5:3: warning: function 'snprintf' is unsafe [-Wunsafe-buffer-usage-in-libc-call]
> > 5 | snprintf(q, 10, "%s", "hello");
> > | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> > foo.c:5:12: note: buffer pointer and size may not match
> > 5 | snprintf(q, 10, "%s", "hello");
> > | ^
> > 1 warning generated.
> > ```
> >
> >
> >
> >
> >
> >
> >
> >
> >
> >
> >
> > Is that as expected? If so, how should snprintf be used to avoid the warning?
>
> Yes, this is expected. According to the C++ Safe Buffers programming model, buffer pointers should be changed to `std::span`. Then `snprintf(span.data(), span.size(), ...)` is considered safe and will not be warned. We may also allow the use of the form `snprintf(span.first(10).data(), 10, ...)` later.
But as @bjope said, we get the warning also for C code, even if I explicitly say e.g. "-std=c11".
So
```clang -Weverything foo.c -c -std=c11```
now yields the new warning.
https://github.com/llvm/llvm-project/pull/101583
More information about the cfe-commits
mailing list