I have a class ArbDouble, made by me, which is basically a wrapper for a mpfr_t
The relevant part of the class for this problem is
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;
}
}
Now, I’m using std::vector to store a matrix of these values e.g.
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);
and this causes a segfault on a linux machine, but not on a mac machine.
The error given by gdb is:
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)
Does anyone knows where the problem can be? I’m not a very good class designer, so, my guess is that somewhere it has a flaw. Any suggestions to it are very welcome!!!
This is a typical case of heap/stack corruption. You probably have an array somewhere that you are writing to, but out of its boundaries. Doing so, you are changing variables of random nearby objects (in this case the
vector) and hence the strange errors on internals of some other library (in this casestd).Since all your class does is call this
mpfr_set of functions, most probably the error is there (unless there is some other code that you are not showing). You could try debugging and finding out the problem in any way you like, but perhaps the easiest solution would be to use valgrind: