【发布时间】:2020-01-21 02:09:49
【问题描述】:
我在做我的项目时需要检查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 error\n";
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 提出了类似的问题。其中之一是How to portably compare std::system_error exceptions to std::errc values?。它所描述的似乎与我正在经历的问题密切相关。所以我针对问题修复的 gcc 版本列表中的 gcc 8.3 进行了测试。
已在所有活动分支上修复,因此将在 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
【问题讨论】:
-
既然你有兴趣检测错误是什么,为什么你有条件地检查
e.what()而不是在if之前输出呢? (可能类似于std::cout << "System error: '" << e.what() << "'\n";。) -
你能提供回溯吗?这也将回答导致段错误的问题是比较还是对
e.code()的调用。此外,如果您打开运行时库的诊断功能,您可以帮助自己,它会捕获并报告一些未定义行为的案例。 -
哦,您可能做错了一件事:您正在使用
gcc进行编译和链接。请改用g++。 coliru.stacked-crooked.com/a/34662c9678a39e10 建议它有效。 -
@UlrichEckhardt 这与我使用的命令无关。无论是 gcc 还是 g++,gnu 编译器集合都会正确调用适当的编译器/链接器。据我所知,“gcc”只是调用预处理器、编译器或链接器的一个方面。而且我实际上试图检查使用
g++而不是gcc是否会使程序不崩溃,结果它仍然崩溃。当我显示堆栈跟踪时,它在operator==中间崩溃,继续调用std::error_category::equivalent