Assignment operator crashes code while i make template of class

0

I'm making a template for vector class in which I'm making vector from an array. But within the class the assignment operator is crashing the code as I can see the return value is some ( Process returned -1073741819 (0xC0000005)).

int i=0;
const int size = 4;
template<class T>
class vector{
public:
    vector()
    {
        x = new T[size];
       for(i=0;i<size;i++)
            x[i] =0 ;
    }
    vector( T *a)   // This part is creating issue if i comment it out code 
// successfully return with value Zero. But with this it doesn't work at all.
    {
      //  cout<<"called";
        for(i=0;i<size;i++)
        {
            x[i] = a[i];
        }
    }
    T  operator *(vector &y)
    {
        T sum = 0;
        for(i=0;i<size;i++)
        {
            sum += this->x[i] + y.x[i];
        }
        return sum;
    }

private:
    T * x; // Type of vector;

};
int main()
{
    int arr1[4] = {2,3,4,5};
    int arr2[4] = {6,7,8,9};
    vector<int> v1;
    vector<int>v2;
    v1 = arr1;  // This call is the culprit. it doesn't work t all.
    v2 = arr2;

    return 0;
}```
c++
class
oop
templates
generic-programming
asked on Stack Overflow Oct 1, 2019 by Problematic

1 Answer

4

You have several issues that lead to the crash and other problems.

The first is that the statement

v1 = arr1;

is equivalent to

v1 = vector<int>(&arr1[0]);

That means a temporary vector<int> object will be created, which invokes the vector(T *a) constructor.

And here the problems start: Because it's a constructor, the object being constructed is uninitialized, as it's the purpose of the constructor to initialize it. That means the member variable x will also be uninitialized and will not be pointing to a valid location.

You need to allocate memory and make x point to that memory, otherwise you dereference the uninitialized pointer which leads to undefined behavior and very likely your crash.


As for the other problems, first of all you miss a destructor, which means that memory allocations don't have anywhere to be free'd. Which in this case actually is good, because since you don't have an actual assignment operator (and rely on the compiler generated assignment operator) the copying in v1 = arr1 will be a shallow copy, that copy only the pointer itself and not the memory it points to.

The shallow copy problem means that for a while you will have two objects whose x member will point to the same memory. And if one object deletes that memory (like when the temporary object mentioned above is destructed) then the second pointer in v1 will no longer be valid.

This is the reason behind the rules of three and five.


User contributions licensed under CC BY-SA 3.0