[clang] [-Wunsafe-buffer-usage] Warning Libc functions (PR #101583)
Ziqing Luo via cfe-commits
cfe-commits at lists.llvm.org
Fri Sep 6 13:09:56 PDT 2024
ziqingluo-90 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.
https://github.com/llvm/llvm-project/pull/101583
More information about the cfe-commits
mailing list