r/programminghelp • • Aug 20 '21

C++ Please help me understand why my C++ program gives segmentation error

#include<iostream>
using namespace std;

const int SIZE = 3;

template <class T>

class Vector
{
    private:
        T* v;
    public:
        Vector()
        {
            v = new T[SIZE];
            for (int i =0; i<SIZE; i++)
            {
                v[i] = 0;
            }
        }

        Vector(T* a)
        {
            for(int i =0; i<SIZE; i++)
            {
                v[i] = a[i];
            }
        }
        
        T operator* (Vector &k)
        {
            T sum =0;
            for(int i =0; i<SIZE; i++)
            {
                sum += this -> v[i] * k.v[i];
            }

            return sum;
        }

        void display()
        {
            for(int i =0; i<SIZE; i++)
            {
                cout<<v[i]<<"\t";
            }
            cout<<endl;
        }
};

int main()
{
    int x[3] = {1, 2, 3};
    int y[3] = {4, 5, 6};
    Vector <int> v1;
    Vector <int> v2;

    v1 = x;
    v2 = y;

    cout<<"v1 = ";
    v1.display();

    cout<<"v2 = ";
    v2.display();
    
    cout<<"v1 * v2 ="<<v1 * v2;

    return 0;
}
5 Upvotes

5 comments sorted by

5

u/KuntaStillSingle Aug 20 '21

The problem is one of your constructor doesn't initialize the array, one fix is to add this line:

Vector(T* a)
{
    v = new T[SIZE]; //add this

}

4

u/ChayanDas19 Aug 20 '21

Thanks man, I now feel 100% stupid.

4

u/KuntaStillSingle Aug 20 '21

Ah no it took me a minute to find that lol. One tip is if you compile with debugging info, valgrind should be able to give you the line number of the segfault.

2

u/[deleted] Aug 20 '21

What's valagrind?

3

u/Shubham_Garg123 Aug 20 '21

Valgrind is a programming tool for memory debugging, memory leak detection, and profiling. Valgrind was originally designed to be a free memory debugging tool for Linux on x86, but has since evolved to become a generic framework for creating dynamic analysis tools such as checkers and profilers.