![](/img/trans.png)
[英]Segmentation fault while iterating a std::set<std::string> in C++
[英]Segmentation fault in C++ with std::cin while macro is defined
我正在尝试解决与堆栈数据结构有关的问题,我有一个堆栈的实现,以及使用它的主要方法,因为我是初学者,这是一个有学习意义的问题,你们能告诉我,为什么我得到这个错误?:
GDB trace:
Reading symbols from solution...done.
[New LWP 24202]
Core was generated by `solution'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 main () at solution.cc:70
70 cin >> N;
#0 main () at solution.cc:70
我的代码如下:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
#define MAX_SIZE 5000000
class Stack
{
private:
int A[MAX_SIZE]; // array to store the stack
int top; // variable to mark the top index of stack.
public:
// constructor
Stack()
{
top = -1; // for empty array, set top = -1
}
// Push operation to insert an element on top of stack.
void Push(int x)
{
if(top == MAX_SIZE -1) { // overflow case.
printf("Error: stack overflow\n");
return;
}
A[++top] = x;
}
// Pop operation to remove an element from top of stack.
void Pop()
{
if(top == -1) { // If stack is empty, pop should throw error.
printf("Error: No element to pop\n");
return;
}
top--;
}
// Top operation to return element at top of stack.
int Top()
{
return A[top];
}
// This function will return 1 (true) if stack is empty, 0 (false) otherwise
int IsEmpty()
{
if(top == -1) return 1;
return 0;
}
// ONLY FOR TESTING - NOT A VALID OPERATION WITH STACK
// This function is just to test the implementation of stack.
// This will print all the elements in the stack at any stage.
void Print() {
int i;
printf("Stack: ");
for(i = 0;i<=top;i++)
printf("%d ",A[i]);
printf("\n");
}
};
int main() {
int N;
cin >> N;
Stack S1;
Stack S2;
for(int i = 0; i < N; i++)
{
int q;
cin >> q;
if(q == 1)
{
int x;
cin >> x;
if(S1.IsEmpty() || S2.IsEmpty())
{
S1.Push(x);
S2.Push(x);
}
else
{
S1.Push(x);
if(x >= S2.Top()) S2.Push(x);
}
}
if(q==2)
{
if(S1.Top() == S2.Top())
{
S1.Pop();
S2.Pop();
}else
{
S1.Pop();
}
}
if(q==3)
{
cout << S2.Top() << endl;
}
}
return 0;
}
如果我将MAX_SIZE变量设置为较小的数字,则代码运行良好,我想知道为什么是这种情况,std :: cin与宏如何相互作用?,我是初学者,很抱歉,如果这是一个简单的问题,那是我第一次在stackoverflow中询问时,
MAX_SIZE
太大。 MAX_SIZE
确定Stack
对象的大小。 由于函数中局部变量的总大小限制为几兆字节(取决于平台),因此您只需超出此大小即可。
在您的情况下,您在main
有两个本地Stack
对象( S1
和S2
),每个对象大约占用20 MB(假设sizeof int
为4)。
不过,这与cin
完全无关。
您的Stack
对象分配在堆栈上。
默认情况下,根据您的平台,每个线程的堆栈限制为1-8 MB。
每个堆栈对象占用20 MB,因此您的堆栈空间不足。 要解决此问题,请将您的代码更改为:
std::unique_ptr<Stack> S1(new Stack());
std::unique_ptr<Stack> S2(new Stack());
这将在堆上分配对象,该对象仅受计算机上可用内存和交换空间大小的限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.