c++ - 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
解决方案
您的调整大小逻辑有误。在你到达这里之前,一切都很好。
p = new T[arraySize];
p = temp;
delete [] temp;
您分配一个新数组,然后立即p
指向 指向的数据temp
。然后你删除 which 指向的数据与 which 指向的数据temp
相同p
,p
指向释放的内存;它是一个悬空引用,通过它访问任何东西是未定义的p
不过,解决起来很简单:去掉分配和删除,只需要有赋值的那一行:
// p = new T[arraySize];
p = temp;
// delete [] temp;
你不需要新的空间p
,temp
已经得到了。把它交给p
. 然后你不删除temp
,因为p
正在管理它。
推荐阅读
- python - ImportError:无法从“bokeh.core.properties”(C:\ProgramData\Anaconda3\lib\site-packages\bokeh\core\properties.py)导入名称“Nullable”
- java - 如何检查 Docker 容器中的应用程序是否忽略 Java 内存选项?
- python - asyncio.Queue 被 1 个协程添加到队列中,1 个协程从队列中获取
- javascript - 当位于页面的特定部分时,我需要使用 JavaScript 突出显示导航栏中与其相关的按钮
- c++ - 两个类与另一个类的成员函数交朋友
- python - 在 TensorFlow WHILE 训练中添加检查点
- python - 当我使用请求模块时,python 给我一个“套接字错误”
- javascript - 用逗号反应原生 js 正则表达式数字,没有点、空格和线
- lua - 我可以使用罗技 lua api 从正常的键盘按下中获取事件吗?
- python - pandas.interpolate 没有给出想要的结果