我试图解决这个问题,但无法纠正次数。我替换我所知道的
class MyStack {
public:
int *arr;
int tops;
MyStack() {
arr=new int(25);
int tops=-1;
}
void push(int x) {
arr[++tops]=x;
}
int pop() {
tops--;
return arr[tops];
}
int top() {
return arr[tops];
}
bool empty() {
bool a;
a= tops==-1?true:false;
return a;
}
};
当我使用其他一些编译器时,它可以工作并且变得完美。
为什么问题再次出现?我有两个问题有相同的错误。
答案 0 :(得分:0)
您在 MyStack
中的所有函数(empty()
除外)都有可能导致非法内存访问。下面是一些可能导致崩溃的类的简单驱动程序代码。
int main()
{
MyStack stack;
int x = stack.pop(); //will crash
int x = stack.top();//will crash
for(int i = 0; i < 26; ++i) {
stack.push(i); //will crash at the last push()
}
return 0;
}
你需要保护:
通过始终验证 arr[]
是否指向有效值,通过 top()
和 pop()
读取 tops
成员。如果它是 -1
,它会在访问 arr[-1]
时由于堆缓冲区下溢而导致崩溃。
通过始终验证 arr[]
以及它是否在为 push()
分配的内存范围内,通过 tops
写入 arr[]
。在代码中,arr[]
由 25 个整数元素支持。如果有 26 个元素压入堆栈会怎样?最后一个是堆缓冲区溢出。