Segfaulting trouble

I am trying to copy the content of one vector into the other.
here is the code that calls the operator= function:

1
2
3
4
 Vector<int> a,b;
  for (int i=0; i<100; i++)
    a.push_back(i);
  b=a;


here is my function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <class T>
Vector<T>& Vector<T>::operator=(const Vector<T>& rhs)
{
  m_size = rhs.m_size;
  m_max_size = rhs.m_max_size;

  for (int i = 0;i < m_size;i++)
  {
    m_data[i] = rhs.m_data[i];
  }

  return *this;
}


When i run the program, it segfaults on line 9 and I can't figure out why.
the size of m_data[i] is still the incorrect size, you will have to delete the data and then recreate the array to the new size, then transfer the data over, if m_data[i] was size 10 but you are trying to put data a new size of 15 into it, it will seg fault

try making the one you are trying to copy to a smaller size and see if it works, it should work, but is the incorrect way of doing it, try my way mentioned above for the said reason above
Last edited on
I thought of that before, but I couldn't get that to work either.
This is what I did:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 m_size = rhs.m_size;
  m_max_size = rhs.m_max_size;

  //resizing to the same size as rhs
  T* temp_data;
  int NewSize = m_max_size;
  temp_data = new T [NewSize];

  for(int i = 0;i < m_size;++i)
  {
    temp_data[i]= m_data[i];
  }

  m_max_size = NewSize;

  if(m_max_size == 1)
    m_max_size=0;

  delete [] m_data;

  m_data = temp_data;


  for (int i = 0;i < m_size;i++)
  {
    m_data[i] = rhs.m_data[i];
  }

  return *this;


I thought this would make m_data the same size as rhs, but it still segfaults, but this time it's on line 11.
Update: I found the problem. Thanks for the help.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

template <class T>
Vector<T>& Vector<T>::operator=(const Vector<T>& rhs)
{
  delete [] this->m_data; // deletes the old array

  this->m_size = rhs.m_size;
  this->m_max_size = rhs.m_max_size;

  this->m_data = new int[this->m_max_size]; //creates the new array

  for (int i = 0;i < this->m_size;i++)
  {
    this->m_data[i] = rhs.m_data[i]; //copies the data
  }

  return *this;
}
Topic archived. No new replies allowed.