0

I am trying to solve a problem related to stack data structure, I have an implementation of a stack, and a main method that uses it, this is a for-learning question as i am a beginner, can you guys tell me, why i get this error?:

    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

my code is the following:

#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;
}

if i set MAX_SIZE variable to a lower number the code runs well, i want to know why is that the case, how std::cin and macros interact??, i am a beginner, sorry if this is a simple question it is the first time that i am asking in stackoverflow,

  • 1) "_Segmentation fault in C with std::cin_" That's impossible. C doesn't have `std::cin`. 2) "_i am a beginner, sorry if this is a simple question_" If you are beginner, you should learn from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of coding randomly. – Algirdas Preidžius May 09 '18 at 15:30
  • sorry i have edited the question, please forgive me – byron perez May 09 '18 at 15:32
  • In addition to Michael Walz: Before `cin >> N;`, there might be allocation of memory for `Stack S1;` and `Stack S2;`. `MAX_SIZE` has direct effect on `sizeof (Stack)`. If you make `MAX_SIZE` big this might exceed your available stack size. Hence, application dies. `cin >> N;` is the closest source code line to address where your appl. dies. Hence, it looks like this was the one which failed but actually it is unrelated. To prove me, just insert an output before `cin >> N;` e.g. `cout << "Start\n";`. I bet then this will seem to fail... – Scheff's Cat May 09 '18 at 15:37
  • What do you mean by _"how std::cin and macros interact?"_ – Jabberwocky May 09 '18 at 15:43
  • MAX_SIZE is too big for stack, bring it to smaller number to get rid off seg fault. Refer here, https://cs.nyu.edu/exact/core/doc/stackOverflow.txt if you wish to change the stack size for your program. – Archie Yalakki May 09 '18 at 15:50
  • oh, maybe i can say, how cin and that macro definition are related in the way that modifing the one the other becomes affected, sorry for my english – byron perez May 09 '18 at 15:50

2 Answers2

2

MAX_SIZE is far too big. MAX_SIZE determines the size of your Stack objects. As the total size of local variables in a function is limited to a few megabytes (depending on the platform), you simply exceed this size.

In your case you have two local Stack objects in main (S1and S2), each of them taking roughly 20 Mbytes (assuming sizeof int is 4).

This is totally unrelated to cin though.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
0

Your Stack objects are allocated on the stack.

By default the stack is limited to something like 1-8 MB per thread depending on your platform.

Each of your stack objects takes up 20 MB so you are running out of stack space. To fix this change your code to:

std::unique_ptr<Stack> S1(new Stack());
std::unique_ptr<Stack> S2(new Stack());

This will allocate your objects on the heap which is only limited by the size of the available memory and swap space on your machine.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60