I'm working through the Stroustrup C++ 11 book, and I ran into a double free exception. I understand that it's freeing the memory twice, but what I don't understand is why it's happening for a function that's passing by copy:
#include <iostream>
using namespace std;
namespace ALL_Vector {
class Vector {
public:
// Intitialize elem and sz before the actual function
Vector(int size) :elem {new double[size]}, sz {size} {};
~Vector() {delete[] elem;};
double& operator[](int i) {
return elem[i];
};
int size() {return sz;};
private:
double* elem;
int sz;
};
void print_product(Vector& y) {
double result {1};
for (auto x = 0; x < y.size() ; x++){
if (y[x] > 0) {result *= y[x]; };
}
cout << "The product of Vector y is: " << result << ", or so it would appear ;)\n";
}
}
/*
Self test of the Vector class.
*/
int main(){
ALL_Vector::Vector myVector(15);
cout << "The size of Vector y is: " << myVector.size() << "\n";
myVector[0] = 12;
myVector[2] = 7;
myVector[3] = 19;
myVector[4] = 2;
ALL_Vector::print_product(myVector);
return 0;
}
print_product() is taking the Vector class and creating a new Vector with duplicated contents? Why would this cause a double free? I'm assuming that RIIA in this instance is somehow interacting with the Vector::~Vector(), something like a race condition?
I know if I change this to pass it's argument by reference it will avoid the double free. I'm trying to better understand the issue with passing by copy.
Thanks!