首页 > 解决方案 > C++ 调整动态数组的大小最多可以处理一定数量的元素,但在某些时候崩溃并出现错误 (0XC0000005)

问题描述

对不起,如果这已经回答过。我搜索了调整动态数组的大小,所有建议似乎都是使用 STL Vector,但我正在做一个任务,重点是制作我自己的最小矢量模板类。

我的向量类需要存储从输入文件读取创建的结构的动态数组。它必须做的一件事是在满时调整大小。它工作到一定程度 - 处理 52207 行中的 5121 行,然后崩溃并出现错误“进程返回 -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

标签: c++arraysvectordynamic-arrays

解决方案


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

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

delete [] temp;

您分配一个新数组,然后立即p指向 指向的数据temp。然后你删除 which 指向的数据与 which 指向的数据temp相同pp指向释放的内存;它是一个悬空引用,通过它访问任何东西是未定义的p

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

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

你不需要新的空间ptemp已经得到了。把它交给p. 然后你不删除temp,因为p正在管理它。


推荐阅读