try catch 无法处理 pthread 内的分段错误
try catch fails to handle segmentation fault inside a pthread
这里的cdp是一个包,里面有一些向量。访问向量时会导致分段错误。 (向量在其范围内访问,我仔细检查了它)。我计划用 try catch 处理这个异常,但它不起作用。
根据 gdb,以下行导致了问题。
int firing_crash=cdp->firing_data[0].size();
函数如下:
bool modified_simplex_solver::check_for_corrupt_cdp(converted_data_pack* cdp)
{
try{
int firing_crash=cdp->firing_data[0].size();
int not_firing_crash=cdp->not_firing_data[0].size();
return false;
}
catch(...)
{ return true;}
}
可以使用 at()
而不是使用 operator[]
(它不执行边界检查)并且如果向量在指定索引处没有元素将导致未定义的行为成员函数。
这个函数:
Returns a reference to the element at specified location pos, with bounds checking.
If pos
is not within the range of the container, an exception of type std::out_of_range
is thrown.
由于 at()
会抛出异常,您可以 catch
它。
您的情况下的用法为:
int firing_crash=cdp->firing_data.at(0).size();
问题中的代码使用异常进行流控制。那是 Java 的事情;在 C++ 中,它是不受欢迎的。在 C++ 中(以及 Java 中)执行此操作的方法是检查数据是否存在:
return firing_data.empty() || not_firing_data.empty();
这里的cdp是一个包,里面有一些向量。访问向量时会导致分段错误。 (向量在其范围内访问,我仔细检查了它)。我计划用 try catch 处理这个异常,但它不起作用。
根据 gdb,以下行导致了问题。
int firing_crash=cdp->firing_data[0].size();
函数如下:
bool modified_simplex_solver::check_for_corrupt_cdp(converted_data_pack* cdp)
{
try{
int firing_crash=cdp->firing_data[0].size();
int not_firing_crash=cdp->not_firing_data[0].size();
return false;
}
catch(...)
{ return true;}
}
可以使用 at()
而不是使用 operator[]
(它不执行边界检查)并且如果向量在指定索引处没有元素将导致未定义的行为成员函数。
这个函数:
Returns a reference to the element at specified location pos, with bounds checking.
If
pos
is not within the range of the container, an exception of typestd::out_of_range
is thrown.
由于 at()
会抛出异常,您可以 catch
它。
您的情况下的用法为:
int firing_crash=cdp->firing_data.at(0).size();
问题中的代码使用异常进行流控制。那是 Java 的事情;在 C++ 中,它是不受欢迎的。在 C++ 中(以及 Java 中)执行此操作的方法是检查数据是否存在:
return firing_data.empty() || not_firing_data.empty();