Below code is a simulation of a problem which I am facing in my project code. In this code, I have a vector in which I have some values. Now, I want to filter out some values from this original vector based on some criteria and store them in a new vector.
Main catch here is the pointer variable in the "node". I am even doing deep copy in order to avoid double free(). But even then it is giving the same exception.
The code:
#include <iostream>
#include <vector>
using namespace std;
class node
{
public:
int a;
double *ptr;
node()
{
a = 0;
ptr = NULL;
}
~node()
{
if(ptr)
{
delete [] ptr;
}
}
};
int main()
{
vector <node> original(10);
cout << "Filling values in Original Copy : " << endl ;
for(int i=0; i<10; i++)
{
original[i].a = 0;
original[i].ptr = new double[20];
}
vector <node> mod2;
cout << "Finding Nodes with value mod 2 : " << endl ;
for(int i=0; i<10; i++)
{
if(original[i].a%2 == 0)
{
node temp;
temp.a = original[i].a;
// Deep Copy
temp.ptr = new double[20];
for(int j=0; j<20; j++)
{
temp.ptr[j] = original[i].ptr[j];
}
mod2.push_back(temp);
temp.ptr = NULL; // To avoid memory deallocation
}
}
return 0;
}