c++ - push_back 导致 sgfault

标签 c++ std

我有一个由我制作的 ArbDouble 类,它基本上是 mpfr_t 的包装器

这个问题类的相关部分是

class ArbDouble
{
private:
    mpfr_t value;

public:
    explicit ArbDouble(long double value_, unsigned long precision) {
        mpfr_init2(value, precision);
        mpfr_set_d(value, value_, MPFR_RNDN);
    }
    explicit ArbDouble(long int value_, unsigned long precision) {
        mpfr_init2(value, precision);
        mpfr_set_ui(value, value_, MPFR_RNDN);
    }

    ArbDouble(){
        mpfr_init(value);
    }

    ArbDouble(unsigned long precision) {
        mpfr_init2(value,precision);
    }
    ArbDouble(const ArbDouble& other) {
        mpfr_init2(value, other.getPrecision());
        mpfr_set(value, other.value, MPFR_RNDN);
    }

    ArbDouble(const mpfr_t& other) {
        mpfr_init2(value, mpfr_get_prec(other));
        mpfr_set(value, other, MPFR_RNDN);
    }

    explicit ArbDouble(char* other, unsigned long precision) {
        mpfr_init2(value, precision);
        mpfr_set_str(value, other, 10, MPFR_RNDN);
    }

    ~ArbDouble() {
        mpfr_clear(value);
    }

    inline unsigned long getPrecision() const
    {
        return mpfr_get_prec(value);
    }
    inline ArbDouble& operator=(const ArbDouble &other)
    {
        mpfr_set_prec(value, other.getPrecision());
        mpfr_set(value, other.value, MPFR_RNDN);
        return *this;
    }
}

现在,我正在使用 std::vector 来存储这些值的矩阵,例如

std::vector<ArbDouble> temp;
temp.push_back(ArbDouble((long int)0,64)); // calling "ArbDouble(long int value_, unsigned long precision)"

std::vector<std::vector<ArbDouble> > currentOrbit;
currentOrbit.push_back(temp);

这会在 linux 机器上导致段错误,但不会在 mac 机器上导致。

gdb给出的错误是:

Program received signal SIGSEGV, Segmentation fault.
0x00000000004069fe in std::vector<std::vector<ArbDouble, std::allocator<ArbDouble> >, std::allocator<std::vector<ArbDouble, std::allocator<ArbDouble> > > >::push_back (this=0xb5daafcc938b13f6, __x=std::vector of length 1, capacity 1 = {...})
    at /usr/include/c++/4.5/bits/stl_vector.h:743
743     if (this->_M_impl._M_finish != this->_M_impl._M_end_of_storage)

有谁知道问题出在哪里?我不是一个很好的类(class)设计师,所以,我猜它在某个地方有缺陷。非常欢迎任何建议!!!

最佳答案

这是堆/堆栈损坏的典型案例。您可能在要写入的某处有一个数组,但超出了它的边界。这样做,您正在更改随机附近对象的变量(在本例中为 vector),因此在某些其他库(在本例中为 std)的内部发生奇怪的错误。

由于您的所有类所做的就是调用此 mpfr_ 函数集,因此很可能存在错误(除非有一些您未显示的其他代码)。您可以尝试以任何您喜欢的方式调试并找出问题,但也许最简单的解决方案是使用 valgrind :

valgrind --leak-check=full ./your_program --args --to --your program

关于c++ - push_back 导致 sgfault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11448494/

相关文章:

c++ - 如何等待此线程池中的所有任务完成?

c++ - 需要确定一个矩阵来对齐两个三角形

c++ - 为大量迭代优化代码

c++ - 关闭由于 boost 库引起的警告

C++ 查找 vector 中的重复符号

python - 更改 QTableModel 中单元格的背景颜色

c++ - 如何在 Visual Studio 2010 中使用 tr1 (tr1::function)?

c++ - 在 C++ 代码中奇怪地使用 void

c++ - 这是一个单数迭代器吗?如果是,我可以将它与另一个迭代器进行比较吗?

c++ - 将 "this"参数显式传递给方法调用