[英]C++ Stack Template SIGTRAP Error
Just started learning about stack templates and ran into an issue while working on the push function whenever I try to free up memory to resize. 刚开始学习堆栈模板时,每当我尝试释放内存以调整大小时,在使用推功能时就会遇到问题。 The function works fine all the way up until it has reached maximum capacity, and then immediately goes into a series of error messages not really picked up by my debugger. 该功能一直很好,直到达到最大容量为止,然后立即进入一系列错误消息,这些消息不是我的调试器真正接收到的。 Here's the header file with the function causing the error, plus the function it calls. 这是带有导致错误的函数的头文件,以及它所调用的函数。
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
template <class T>
class MyStack
{
private:
T* data;
int topVal;
int capacity;
public:
MyStack()
{
capacity = 10;
topVal = 0;
data = new T[capacity];
}
~MyStack()
{
delete [] data;
data = 0;
}
void push(T);
T pop();
T top();
bool isFull();
bool isEmpty();
string toString();
};
template <class T>
void MyStack<T>::push(T value)
{
if(!isFull())
{
data[++topVal] = value;
}
else
{
capacity *= 2;
T* holdPtr = new T[capacity];
for(int i = 0; i <= topVal; ++i)
holdPtr[i] = data[i];
delete [] data; //This is where the error is occurring
data = holdPtr;
data[++topVal] = value;
}
}
template <class T>
bool MyStack<T>::isFull()
{
if(topVal < capacity)
return false;
else
return true;
}
Any help would be greatly appreciated. 任何帮助将不胜感激。
EDIT: Problem solved! 编辑:问题解决了! Thanks for all the help! 感谢您的所有帮助!
Two (related) problems: 两个(相关)问题:
1) With an empty stack, topval == 0
. 1)对于空堆栈, topval == 0
。 But your push
puts the element in data[++topVal]
- ie, data[1]
. 但是您的push
将元素放入data[++topVal]
-即data[1]
。 data[0]
is never used. 永远不会使用data[0]
。
2) When topval == 9
and capacity == 10
, your isFull()
returns false
and your push
tries to stores the value in data[10]
, which is out-of-bounds and corrupts memory. 2)当topval == 9
并且capacity == 10
, topval == 9
isFull()
返回false
并且您的push
尝试将值存储在data[10]
,该值越界并损坏内存。
Also, your push
should either take value
by const
reference or (if you are using C++11) use std::move
. 另外,您的push
应该通过const
引用获取value
,或者(如果使用的是C ++ 11)请使用std::move
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.