dimanche 23 avril 2017

Class (C++) Overloaded Operators Causes Memory Leak

I'm developing C++ library based on GMP to work with bigintegers and bigdecimals. Class:

class bigdecimal {
    public: mpf_t x;
    // and overloaded constructors methods... 
    // I've provided an empty destructor

Overloaded assignment operator:

void operator = (const bigdecimal& R ) { 
         mpf_set(x, R.x);
      }

Overloaded + operator:

inline bigdecimal operator +(biginteger& lhs, bigdecimal rhs){
    bigdecimal sum = bigdecimal(lhs);
    sum += rhs;
    return sum;
}

Based on overloaded += operator:

bigdecimal& bigdecimal::operator += (const bigdecimal& a){
    mpf_add(this->x, this->x, a.x);
    return *this;
}

The test code:

bigdecimal p1 = bigdecimal(2, 128);//128 is precision in bits here
bigdecimal p2 = bigdecimal(3, 128);
bigdecimal p3 = bigdecimal(4, 128);
int main() {
    p1 = p1 * p3 ;
    p1.printbigdecimal();
    p2.printbigdecimal();
    p3.printbigdecimal();

    for (unsigned long long int  i = 0; i < 1000000000; i++){
        p3 = p1 + p2;

    }
    p1.printbigdecimal();
    p2.printbigdecimal();
    p3.printbigdecimal();
    return 0;
}

Causes a memory leak , console output:

➜  GMP_C git:(master) ✗ g++ -Ofast -o -Wall -c -std=c++11 bigdecimal.cc -lgmp
➜  GMP_C git:(master) ✗ g++ -Ofast -o -Wall -c -std=c++11 bigdecimal.h -lgmp 
➜  GMP_C git:(master) ✗ time ./test_mult                                     
0.8e1
0.3e1
0.4e1
[2]    23395 killed     ./test_mult
./test_mult  19.46s user 6.62s system 63% cpu 41.084 total

In method "+=" is one object creation, in "+" also one, in every loop cycle destructor is called twice as should be; but if I add a line

mpf_clear (x);

To destructor - it corrupt memory.
The issue is how to clear the mpf field "x", when the destructor clears objects in the loop like above? If you want have a look for the whole, I could add a link in a commentary.

Aucun commentaire:

Enregistrer un commentaire