I am running the below minimal working example for storing some GNU multiprecision library (GMP) numbers mpz_class in a vector and then clearing the memory allocated as below:
#include <limits>
#include <iostream>
#include <algorithm>
#include <vector>
#include <math.h>
#include <stdio.h>
#include <gmp.h>
#include <gmpxx.h>
std::vector<mpz_class> GenVector(int n) {
std::vector<mpz_class> result;
mpz_class x("45642346"), y("45345345");
for(int k=0; k<n; k++) {
result.push_back(x + k*y);
}
return result;
}
int main() {
int n(5);
std::vector<mpz_class> states = GenVector(n);
for(size_t k=0; k<states.size(); k++) std::cout<<states[k].get_mpz_t()<<std::endl;
mpz_clear(states[0].get_mpz_t()); //OFFENDING LINE
return 0;
}
Compiling and executing this gives
45642346
90987691
136333036
181678381
227023726
*** glibc detected *** ./Test: double free or corruption (fasttop): 0x000000000181d220 ***
======= Backtrace: =========
The answers are correct but there seems to be a memory corrpution; but if I change the index in the offending line from 0 to anything else like, say, 1, then there is no problem. Can somebody clarify what is going on? Thanks.
Note: Command for compilation and linking is g++ Program.cpp -o program.exe -lgmpxx -lgmp