【问题标题】:try catch fails to handle segmentation fault inside a pthreadtry catch 无法处理 pthread 内的分段错误
【发布时间】:2019-01-14 04:27:26
【问题描述】:

这里的 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;}
}

【问题讨论】:

  • 你只能catch 一些你throw 的东西。这里没有throw。段错误不是 C++ 异常。

标签: c++ segmentation-fault pthreads try-catch


【解决方案1】:

您可以使用at() 成员函数,而不是使用operator[](不执行边界检查)并且如果向量在指定索引处没有元素会导致未定义的行为。

at( size_type pos );

这个函数:

  • 返回对指定位置 pos 的元素的引用,并进行边界检查

  • 如果pos不在容器范围内,会抛出std::out_of_range类型的异常

由于at()会抛出异常,你可以catch它。

在你的情况下的用法是:

int firing_crash=cdp->firing_data.at(0).size();

【讨论】:

    【解决方案2】:

    问题中的代码使用异常进行流控制。那是Java的事情;在 C++ 中,它不受欢迎。在 C++(以及 Java)中执行此操作的方法是检查数据是否存在:

    return firing_data.empty() || not_firing_data.empty();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2022-06-16
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-25
      相关资源
      最近更新 更多