Oli*_*ung 2 c++ std clang undefined-behavior compiler-bug
以下 C++ 程序是否包含任何未定义的行为?
int
main()
{
struct entry
{
uint32_t hash;
uint32_t idx;
};
entry arr[31] = {
{ 7978558, 0}, { 9241630, 1}, { 65706826, 2},
{ 639636154, 3}, {1033996244, 4}, {1225598536, 5},
{1231940272, 6}, {1252372402, 7}, {2019146042, 8},
{1520971906, 9}, {1532931792, 10}, {1818609302, 11},
{1971583702, 12}, {2116478830, 13}, { 883396844, 14},
{1942092984, 15}, {1274626222, 16}, { 333950222, 17},
{1265547464, 18}, { 965867746, 19}, {1471376532, 20},
{ 398997278, 21}, {1414926784, 22}, {1831587680, 23},
{ 813761492, 24}, { 138146428, 25}, { 337412092, 26},
{ 329155246, 27}, { 21320082, 28}, {1751867558, 29},
{1155173784, 30},
};
std::sort(std::begin(arr), std::end(arr),
[](entry a, entry b) { return a.hash <= b.hash; });
}
Run Code Online (Sandbox Code Playgroud)
当我使用 gnu c++ 编译器或 12.0.0 之后的任何 clang/llvm 编译时,程序运行正常。但是,当我使用 clang 版本 12.0.0(我的 Mac 笔记本电脑上附带的默认编译器)编译它时,它崩溃了,如下所示std::sort():
$ g++ --version
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 12.0.0 (clang-1200.0.32.2)
Target: x86_64-apple-darwin21.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
$ g++ -g -std=c++11 bug.cc
$ ./a.out
Segmentation fault: 11
Run Code Online (Sandbox Code Playgroud)
另外,如果我将其更改为使用 std::vector 而不是固定大小的数组。使用 clang 12.0.0 编译时, std::sort() 将永远不会返回
use*_*522 10
是的,比较器不是严格的弱排序,它违反了 的前提条件std::sort,导致未定义的行为。
对于两个参数a和b(可能相同),严格的弱排序comp永远不应该将comp(a,b)和 都计算comp(b,a)为true。换句话说,它应该模拟内置函数的行为<,而不是<=.
所以在你的代码中应该是<,而不是<=,使其成为严格的弱排序。
| 归档时间: |
|
| 查看次数: |
145 次 |
| 最近记录: |