比较 std::system_error::code() 和 std::errc::invalid_argument 时



我需要检查std::system_error做我的项目的错误代码。 但是当我这样做时,我最终得到了SIGSEGV.

foo.cpp

#include <thread>
#include <iostream>
#include <system_error>
int main(void)
{
std::thread t1;
try
{
t1.join();
}
catch (const std::system_error& e)
{
std::cout << "System errorn";
if (e.code() == std::errc::invalid_argument) // here in the operator==(), running into SIGSEGV 
{
std::cout << e.what() << "n";
}
else
{
throw;
}
}
return 0;
}

Makefile

.PHONY: all clean
all: foo
SRCS := $(shell find . -name '*.cpp')
OBJS := $(SRCS:.cpp=.o)
foo: $(OBJS)
gcc -o $@ $^ -lstdc++ -lpthread
%.o: %.cpp
gcc -std=c++17 -Wall -c -g -O0 -pthread -o $@ $<
clean:
rm -rf foo *.o

我的 gcc 版本:

$ gcc --version
gcc (GCC) 7.2.1 20170829 (Red Hat 7.2.1-1)
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

当我发布这个问题时,StackOverflow提出了类似的问题。其中之一是如何移植地比较 std::system_error 异常与 std::errc 值?。其中描述的内容似乎与我正在经历的问题密切相关。所以我针对 gcc 8.3 进行了测试,该版本在问题修复 gcc 版本列表中。

固定在所有活动分支上,因此将在 6.5、7.4、8.3 中修复 和 9.1 版本。

但它似乎仍未修复,或者只是另一个问题:

$ gcc --version
gcc (GCC) 8.3.1 20190311 (Red Hat 8.3.1-3)
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ make
gcc -std=c++17 -Wall -c -g -O0 -pthread -o foo.o foo.cpp
gcc -o foo foo.o -lstdc++ -lpthread
$ ./foo
System error
Segmentation fault (core dumped)

有什么想法可以解决此问题并检测发生system_error时实际是哪个错误?


编辑:使用 gdb 添加回溯信息

Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x0000003603269ca2 in std::error_category::equivalent(std::error_code const&, int) const () from /usr/lib64/libstdc++.so.6
Missing separate debuginfos, use: debuginfo-install glibc-2.12-1.192.el6.x86_64 libgcc-4.4.7-17.el6.x86_64 libstdc++-4.4.7-17.el6.x86_64
(gdb) where
#0  0x0000003603269ca2 in std::error_category::equivalent(std::error_code const&, int) const () from /usr/lib64/libstdc++.so.6
#1  0x000000000040285f in std::operator== (__lhs=..., __rhs=...) at /opt/rh/devtoolset-7/root/usr/include/c++/7/system_error:299
#2  0x0000000000402628 in main () at foo.cpp:17

似乎我使用的 gcc 工具链版本与构建 libstdc++ 的版本之间的差异是罪魁祸首。

C++使用现代编译器编译的项目,但链接到过时的libstdc++

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=91876

至于显示不会崩溃的结果 http://coliru.stacked-crooked.com/a/34662c9678a39e10,我想它没有问题,因为库和编译器版本匹配。

最新更新