new int []抛出'Access Violation'异常

时间:2011-04-17 06:00:21

标签: c++ dynamic vector c++builder access-violation

我一直在研究自定义Vector类。在Microsoft编译器上一切都运行得很好,但是当我在Borland上尝试它时,我得到了一个非常奇怪的错误。

Borland在插入函数内抛出异常; 正好在调用复制构造函数“Vector temp(* this);”时在

“array_ = new int [rhs.size_];”线

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];
    }
}

这是我的复制构造函数;

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];
    }
}

最后这是main();

 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);

奇怪的是第一次插入调用(a.insert(99,3))工作正常,它在第二次调用时崩溃(a.insert(98,0))

这是完整的头文件

namespace CS170
 {
    class SubscriptError
    {
     public:
       SubscriptError(int Subscript) : subscript_(Subscript) {};
       int GetSubscript(void) const { return subscript_; }

     private:
    int subscript_;
    };

class Vector
{
public:

    static const int NO_INDEX = -1;

    struct SortResult
    {
        unsigned compares;
        unsigned swaps;
    };

    // Default constructor
    Vector(void);

    // Destructor
    ~Vector();

    // Copy constructor
    Vector(const Vector& rhs);

    // Constructor to create a Vector from an array
    Vector(const int array[], unsigned size);

    // Adds a node to the front of the list
    void push_back(int value);

    // Adds a node to the end of the list
    void push_front(int value);

    // Removes the last element. Does nothing if empty.
    void pop_back(void);

    // Removes the first element. Does nothing if empty.
    void pop_front(void);

    // Inserts a new node at the specified position. Causes an
    // abort() if the position is invalid. (Calls check_bounds)
    void insert(int value, unsigned position) throw(SubscriptError);

    // Removes an element with the specified value (first occurrence)
    void remove(int value);

    // Deletes the underlying array and sets size_ to 0
    void clear(void);

    // Return true if the vector is empty, otherwise, false
    bool empty(void) const;

    // Assignment operator
    Vector& operator=(const Vector& rhs);

    // Concatenates a vector onto the end of this vector.
    Vector& operator+=(const Vector& rhs);

    // Concatenates two Vectors.
    Vector operator+(const Vector& rhs) const;

    // Subscript operators.
    int operator[](unsigned index) const throw(SubscriptError);
    int& operator[](unsigned index) throw(SubscriptError);

    // Returns the number of elements in the vector.
    unsigned size(void) const;

    // Returns the size of the underlying array
    unsigned capacity(void) const;

    // The number of memory allocations that have occurred
    unsigned allocations(void) const;

    // This searches the vector using a binary search instead
    // of a linear search. The data must be sorted. Returns
    // the index. If not found, returns CS170::Vector::NO_INDEX.
    // DO NOT SORT THE DATA IN THIS FUNCTION!!    
    int bsearch(int value) const;

    // Sorts the elements using a selection sort. 
    // Returns the number of swaps/comparisons that occurred.
    SortResult selection_sort(void);

    // Sorts the elements using a bubble_sort.
    // Returns the number of swaps/comparisons that occurred.
    SortResult bubble_sort(void);

    void swap(int &a, int& b);

    void swapv(Vector &other);

    void reverse(void);

    bool operator==(const Vector& rhs) const;

    void shrink_to_fit(void);

private:
    int *array_;        // The dynamically allocated array
    unsigned size_;     // The number of elements in the array
    unsigned capacity_; // The allocated size of the array
    unsigned allocs_;   // Number of allocations (resizes)

    // Private methods...
    void check_bounds(unsigned index) const throw(SubscriptError);
    void grow(void);

    // Other private methods...
};

   }// namespace CS170

        #endif // VECTOR_H

3 个答案:

答案 0 :(得分:2)

在我看来,第一次打电话给insert()时会造成伤害。插入元素时,还必须为成员array_增加分配的字节数。您只是增加了size_,但是增加实际array_的大小呢?

例如,insert()

中正在发生类似下面的内容
int size = 5;
int *p = new int[size];
// ... populate p[i] (i = 0 to i = size - 1)
size ++;
p[size - 1] = VALUE; // oops ... incremented 'size' but before that reallocate to 'p'

调用后,首先插入堆栈已经损坏。所以第二次它崩溃了。只需根据相应的代码更改进行验证。

旁注,

  • 我觉得你可以写insert(),更加优化。我觉得不需要复制临时的完整Vector<>
  • 此外,尝试为array_分配比实际需要更多的字节数。因此,您不必多次重新分配
  • 尝试从STL查看实际vector的源代码,以提高效率。

答案 1 :(得分:2)

array_insert()的{​​{1}}不会(明显)调整大小。这意味着您将始终在其分配的内存的末尾写入一个元素。

复制整个阵列(两次)会导致非常昂贵的插入。您在std::vector中无法实现的目标是什么?

答案 2 :(得分:0)

在插入函数中,您不为新插入的项目分配内存,并且在第一次插入后,复制ctr尝试读取它正在抛出异常的行上的未分配内存。解决方案是最初分配更多内存(这就是为什么容量用于典型的矢量实现)或增加每个插入上分配的数组。您必须在两个解决方案上实现重新分配,但在第一个解决方案中,它将不常被调用。