1

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;
}
Toseef Khilji
  • 17,192
  • 12
  • 80
  • 121
Vasu
  • 13
  • 2
  • why dont you use a vector or some std data structure instead of `ptr` – UmNyobe Dec 27 '13 at 09:38
  • 1
    @UmNyobe: Actually, It is an existing code. I am just adding a new functionality to the code that is why I can't change the node structure. – Vasu Dec 27 '13 at 09:46

2 Answers2

2

The node class violates the rule of three. You need to add a copy constructor and a copy assignment operator.

Without this, whenever an instance of node is copied around (as is routinely done by std::vector<node>), your code ends up double-deleting memory.

The hack of manually setting temp.ptr to NULL after adding tmp to the vector helps somewhat. However, this is neither a clean solution nor a robust one (since it doesn't take care of all circumstances when this needs to be done).

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Each time you are pushing and element into the mod2 vector, it is increasing its size. In order to do that it is destructing the previously held memory and allocating a new chunk to it. While doing that it is calling the default copy constructor which is by default doing the shallow copy.

You can solve this problem by:

  1. Overloading the default copy constructor

  2. Reserving the size for mod2 in advance (as you know it can't be bigger than original vector)

    EDIT: You can also check the rule of three as metioned by @NPE.

Community
  • 1
  • 1
techbull
  • 118
  • 2
  • 16