-2

Why am I getting segmentation fault:11 in this piece of code? Is there a shortage of memory on my Mac? Or is there some other reason? I have MacBook Air RAM 8GB.

template<class T>
class vecto
{
     T *v;
     int size;
public:
     vecto(int m)
     {
          size=m;
          v=new T[m];
          for(int i=0; i<size; i++)
               v[i]=0;
          cout<<"inside constructor 1."<<endl;
     }
     vecto(T *a)
     {
          for(int i=0; i<size; i++)
               v[i]=a[i];
          cout<<"inside constructor 2."<<endl;
     }
};

int main()
{
     int a1[3] = {1,2,3};
     float a2[3] = {4,5,6};
     vecto<int> v1(3);  //constructor 1 called
     vecto<float> v2(3); //constructor 1 called
     v1=a1;  //constructor 2 called
     v2=a2; //constructor 2 called
     return 0;
}
Manvir
  • 769
  • 1
  • 7
  • 15
MAVERICK
  • 41
  • 1
  • 9
  • 1
    ***Is there a shortage of memory on my Mac?*** Unlikely. – drescherjm Aug 23 '17 at 16:18
  • 6
    Use a debugger to check with line the segmentation fault happens. – nwp Aug 23 '17 at 16:19
  • 1
    You should look at using a debugger, it will show you the line of code that triggered it and let you inspect your programs state (e.g. see if a pointer or index has an unexpected value) – Fire Lancer Aug 23 '17 at 16:19
  • In `vecto(T *a)` how many elements does `v` point to? – NathanOliver Aug 23 '17 at 16:20
  • You also will need to look at the rule of 3/5/0. You are not freeing your dynamically allocated memory but when you do you will run into trouble if you fail to implement the other required functions. – drescherjm Aug 23 '17 at 16:24
  • 1
    The second ctor does not initialize v before assigning values to it. you basically are accessing an uninitialized pointer. Note that where you commented ctor 2 is called there are 2 actions being made, a temporary vector will be built using a1 and then the copy ctor will be called to copy the temporary vector into v1. – Jonathan Aug 23 '17 at 16:24
  • Yes, there's another reason. [Go here to fix the problem](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – n. m. could be an AI Aug 23 '17 at 18:47

1 Answers1

1

The call

v1=a1;  //constructor 2 called

Tries to make a copy, but you haven't initialized the vecto yet and you can't as constructor 2 doesn't know the size of 'T *a', anyway when it has finished it would try to call the copy constructor which would also fail.

Instead use an assignment operator.

vecto & operator= ( const T * a ) {
    for(int i=0; i<size; i++)
        v[i]=a[i];
    std::cout<<"inside copy assign"<<std::endl;
    return *this;
}
Surt
  • 15,501
  • 3
  • 23
  • 39