sro*_*men 10 c++ gcc glibc fortify-source c++20
我有这段代码(让我们命名它problem.cpp
):
#include <string>\n\nusing str = std::wstring;\nstatic str foo(str text = str())\n{\n text.resize(4);\n return text;\n}\n\nint main()\n{\n str a = foo();\n return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n-O1
使用C++20 一致性 ( )调用 GCC(版本 12.2.1)g++ problem.cpp -Werror -O1 -std=c++20
会导致此错误:
In file included from /usr/include/features.h:490,\n from /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/x86_64-pc-linux-gnu/bits/os_defines.h:39,\n from /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/x86_64-pc-linux-gnu/bits/c++config.h:655,\n from /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/string:38,\n from problem.cpp:1:\nIn function \xe2\x80\x98wchar_t* wmemcpy(wchar_t*, const wchar_t*, size_t)\xe2\x80\x99,\n inlined from \xe2\x80\x98static constexpr std::char_traits<wchar_t>::char_type* std::char_traits<wchar_t>::copy(char_type*, const char_type*, std::size_t)\xe2\x80\x99 at /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/bits/char_traits.h:558:16,\n inlined from \xe2\x80\x98constexpr std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(std::__cxx11::basic_string<_CharT, _Traits, _Alloc>&&) [with _CharT = wchar_t; _Traits = std::char_traits<wchar_t>; _Alloc = std::allocator<wchar_t>]\xe2\x80\x99 at /usr/lib/gcc/x86_64-pc-linux-gnu/12/include/g++-v12/bits/basic_string.h:675:23,\n inlined from \xe2\x80\x98str foo(str)\xe2\x80\x99 at problem.cpp:7:9,\n inlined from \xe2\x80\x98int main()\xe2\x80\x99 at problem.cpp:12:14:\n/usr/include/bits/wchar2.h:39:10: error: call to \xe2\x80\x98__wmemcpy_chk_warn\xe2\x80\x99 declared with attribute warning: wmemcpy called with length bigger than size of destination buffer [-Werror=attribute-warning]\n 39 | return __glibc_fortify_n (wmemcpy, __n, sizeof (wchar_t),\n | ^~~~~~~~~~~~~~~~~\ncc1plus: all warnings being treated as errors\n
Run Code Online (Sandbox Code Playgroud)\n有趣的是,我无法通过使用std::string
(与 相比std::wstring
)、使用较低的调整大小值或低于 C++20 或 的任何内容来触发此错误O1
。
对我来说,这段代码看起来并不可疑。不幸的是,我无法用 Godbolt 重现这一点。也许 Godbolt 使用另一个和/或未强化的 glibc 版本?我在 Gentoo Linux 上使用 glibc 版本 2.36,但我也在 Ubuntu 上看到过这个。然而,在我怀疑 glibc 或编译器中存在错误之前,我会先联系这里,看看这实际上是否是误报。
\n有任何想法吗?
\n编辑:与此同时,我可以使用 Godbolt 重现类似的错误: https: //godbolt.org/z/joPaYKK11
\n这是 中的一个错误libstdc++
。
开发人员反应非常快,并修复了12.3 的问题。
感谢srohmen、KamilCuk和user17732522对上述问题和评论的有益讨论!
该警告来自在触发警告的情况下从未执行的代码分支。修复方法是通过插入__builtin_unreachable()
.
C++23引入的std::unreachable
还有一个任务,告诉编译器代码中的这个分支永远不会被执行。请注意,它不一定等同于 GCC 的__builtin_unreachable()
,因为std::unreachable
仅保证未定义的行为!在实践中,您必须测试是否std::unreachable
解决了具体问题,或者是否必须依赖于特定于编译器的定义良好的内置函数。
归档时间: |
|
查看次数: |
193 次 |
最近记录: |