new int[] throws 'Access Violation' exception

I've been working on custom Vector class. Everything works perfectly fine on Microsoft compiler, however when I try it on Borland I'm getting a really strange error.

Borland throws the exception inside the insert function; Exactly when calling the copy constructor "Vector temp(*this);" at the

"array_ = new int[rhs.size_];" line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void Vector::insert(int value, unsigned position) throw(SubscriptError)
{
    check_bounds(position);
    Vector temp(*this);
    int tmpSize= size_;
    temp.size_++;
    size_++;
    for (unsigned int i=tmpSize; i > position; i--)
    {
        temp[i] = temp[i-1];
    }
    temp[position] = value;

   //array_= temp.array_;
    for(unsigned int i = 0; i < size_; i++)
    {
        array_[i]= temp.array_[i];
    }
}


here is my copy constructor(where the error is thrown);

1
2
3
4
5
6
7
8
9
Vector::Vector(const Vector& rhs)
{
    array_ = new int[rhs.size_];
    size_ = rhs.size_;
    for(unsigned int i = 0; i < rhs.size_; i++)
    {
        array_[i] = rhs.array_[i];
    }
}


and finally this is the main();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 std::cout << "push_back 5 integers:\n";
 for (int i = 0; i < 5; i++)
 {
  a.push_back(i);
   Print(a);
 }

std::cout << "insert(99, 3):\n";
a.insert(99, 3);
Print(a);
std::cout << "insert(98, 0):\n";
a.insert(98, 0);
Print(a);
std::cout << "insert(97, 6):\n";
a.insert(97, 6);
Print(a);


The strange thing is first insert call(a.insert(99, 3)) works fine, it crashes when it comes to the second call(a.insert(98, 0))



You're having an out-of-bounds access in insert.
In the first iteration of the moving loop, you're trying to assign the element at index size_+1 to size_ - that's two elements off the mark. You're never resizing the array anywhere.
And there's absolutely no reason to perform two full copies of the entire vector every time you insert an element. That'll result in terrible performance.
Last edited on
Topic archived. No new replies allowed.