gpt4 book ai didi

c++ - 结束时控制台崩溃(循环)未超出范围错误

转载 作者:行者123 更新时间:2023-11-28 04:57:00 24 4
gpt4 key购买 nike

您好,我正在为我的研究创建一个简单的 vector 类。只是为了存储变量 LONG我保持一切简单。当我构建时没有返回错误/警告。然后运行程序后,它可以运行但程序崩溃。

代码 vector .h

class Vector{
public:
Vector();
void add(long i);
void getData();
private:
long *anArray;
long maxSize;
long position;
void reSize(int i);

};

vector .cpp

    Vector::Vector(){
maxSize = 2;
anArray = new long[maxSize];
position = 0;
}

void Vector::add(long i){
if(position==maxSize-1)
reSize(maxSize * 2);

anArray[position] = i;
position++;
}

void Vector::reSize(int i){
long *temp = new long[maxSize];
for(int i =0; i<maxSize; i++)
{
temp[i] = anArray[i];
}
delete[] anArray;
anArray = temp;
}

void Vector::getData(){

for(int i = 0; i<position; i++)
{
cout << "Element" << i+1 << " : " << anArray[i] << endl;
}
}

主要

    int main()
{
Vector vecStore;



for(int i = 0; i < 1000; i++)
{
long a;
vecStore.add(a = i + 1);
}

cout << "GET DATA _________ :: " << endl;
vecStore.getData();
return 0;
}

如果输入数据很小(例如 10-20),程序不会崩溃但是当我将它更改为 100 甚至更大时。该程序有时会崩溃,有时不会。

我做错了吗?

最佳答案

void Vector::add(long i){
if(position==maxSize-1)
reSize(maxSize * 2);

anArray[position] = i;
position++;
}

position==maxSize-1 时,调用 reSize 使数组的大小加倍。不幸的是,reSize 坏了。

void Vector::reSize(int i){
long *temp = new long[maxSize];
for(int i =0; i<maxSize; i++)
{
temp[i] = anArray[i];
}
delete[] anArray;
anArray = temp;
}

从未使用过参数i。这应该是 Vector 的新大小,但新数组分配的 maxSize 与之前的数组相同。 maxSize 保持不变。

返回add,数据存储在position 并且position 增加1。这意味着在下一个 add position 等于 maxSize,所以检查以防止数组溢出,

if(position==maxSize-1)

不会做你想做的事,程序会写到数组的边界之外。从那里开始,position 不断变大,永远不会等于 maxSize 减一,并且写得更远越界,这在这一点上并不重要。 Undefined Behaviour has already been invoked ,而克罗姆只知道会发生什么。也许程序崩溃了,也许程序稍后崩溃了,也许它做了一些奇怪的事情,甚至可能它看起来一切正常。

你想要更多的东西

void Vector::reSize(int newSize){ // note more descriptive name
long *temp = new long[newSize]; // using new size, not old size
for(int i =0; i<maxSize; i++)
{
temp[i] = anArray[i];
}
delete[] anArray;
anArray = temp;
maxSize = newSize; // store new size.
}

Vector 还需要一个析构函数来清理 anArray,但为了正确修复此错误,这里有一些推荐阅读:What is The Rule of Three?

关于c++ - 结束时控制台崩溃(循环)未超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46940387/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com