C++ 调整动态数组的大小最多可以处理一定数量的元素,但有时会因错误 (0XC0000005) 而崩溃

C++ reszing dynamic array works up to a certain number of elements, but at some point crashes with error (0XC0000005)

抱歉,如果之前已经回答过这个问题。我搜索了调整动态数组的大小,所有的建议似乎都是使用 STL Vector,但我正在做一个作业,重点是制作我自己的最小矢量模板 class。

我的向量 class 需要存储从输入文件读取创建的动态结构数组。它必须做的一件事是在满时调整大小。它工作到一定程度 - 处理 52207 行中的 5121 行,然后因错误 "Process returned -1073741819 (0XC0000005)" 而崩溃。

我环顾四周,发现这是一个内存分配错误。我是编程和 C++ 的新手,我对我的程序中的原因感到困惑。我假设它在我调整数组代码的大小中。任何帮助将不胜感激!

我的矢量模板代码:

#ifndef VECTOR_H
#define VECTOR_H

#include <iostream>

using namespace std;

template <class T>
class Vector {
public:
  /// Constructor
  Vector();
  /// Copy constructor
  Vector(const Vector<T>& otherVector);
  /// Destructor
  virtual ~Vector();
  /// assignment operator
  const Vector<T>& operator= (const Vector<T>&);
  /// methods
  void addElement(const T& newElement);
  T getElement(int index) const;
  int getLength() const;

protected:
  int arraySize;
  int length;
  T *p;

};

template <class T>
Vector<T>::Vector()
{
  arraySize = 10;
  length = 0;

  p = new T[arraySize];
}

template <class T>
Vector<T>::Vector(const Vector& otherObject)
{
  arraySize = otherObject.arraySize;
  length = otherObject.length;

  p = new T[arraySize];

  for(int i = 0; i < length; i++)
    p[i] = otherObject.p[i];
}

template <class T>
Vector<T>::~Vector()
{
  delete [] p;
}

template <class T>
const Vector<T>& Vector<T>::operator= (const Vector<T>& newVector)
{
  if(this != &newVector)
  {
    delete [] p;
    arraySize = newVector.arraySize;
    length = newVector.length;

    p = new T[arraySize];

    for(int i = 0; i < length; i++)
        p[i] = newVector.p[i];
  }
  return *this;
}

template <class T>
void Vector<T>::addElement(const T& newElement)
{
    if(length == arraySize)
    {
       // create a new resized array
      T *temp;
      temp = new T[arraySize*2];

        // copy elements of p into temp
      for(int i = 0; i < length; i++)
      {
        temp[i] = p[i];
      }

        // delete p and create new p and set equal to temp
      delete [] p;
      arraySize *= 2; // set array size to double
      p = new T[arraySize];
      p = temp;

        // delete temp array
      delete [] temp;

        // add new element and incerement length;
      p[length] = newElement;
      length++;

    }
    else
    {
      p[length] = newElement;
      length++;
    }
}

template <class T>
T Vector<T>::getElement(int index) const
{
  return p[index];
}

template <class T>
int Vector<T>::getLength() const
{
  return length;
}

#endif

您的调整大小逻辑有误。在您到达这里之前,一切都很好。

p = new T[arraySize];
p = temp;

delete [] temp;

您分配一个新数组,然后立即让 p 指向 temp 指向的数据。然后删除 temp 指向的数据,这与 p 相同,这意味着 p 指向释放的内存;它是一个悬空引用,未定义通过 p

访问任何内容

不过修复起来很简单:去掉分配和删除,只需要有赋值的那一行:

  // p = new T[arraySize];
  p = temp;
  // delete [] temp;

您不需要 p 的新 space,temp 已经有了。交给p就行了。然后你不删除 temp,因为 p 正在管理它。