dimanche 14 octobre 2018

"Segmentation fault: 11" when creating a big array [duplicate]

This question already has an answer here:

I'm trying to create an implementation of a stack using an array and have a problem with a segmentation fault. Below is my code.

Stack.hpp

#ifndef STACK_H
#define STACK_H

#include <iostream>
#define MAX_ARRAY_SIZE 2000000

using namespace std;

class Stack {
    int head; //
public:
    Stack() {
        head = 0;
    }
    int a[MAX_ARRAY_SIZE]; // Maximum size of Stack
    void push(int x); // Add x
    int pop(); // Remove one element
    int& top(); // Return reference to the top element
    int size(); // Return number of elements
    bool empty(); // Return 0 if the stack is empty
};

void Stack::push(int x) {
    if (head == MAX_ARRAY_SIZE) {
        cout << "Stack Overflow" << endl;
    }
    else {
        a[head++] = x;
        cout << "Added " << x << endl;
    }
}

int Stack::pop() {
    return a[--head];
}

int& Stack::top() {
    return a[head - 1];
}

int Stack::size() {
    return head;
}

bool Stack::empty() {
    if (head == 0) return true;
    else return false;
}

#endif // STACK_H

Main.cxx

#include <iostream>
#include <vector>
#include <string>
#include "Stack.hpp"

int main() {
    int value;

    Stack s;
    std::string x;
    std::vector<string> v;

    while (std::cin >> x) {
        v.push_back(x);
        if (v.back() == "A") {
            std::cin >> value;
            s.push(value);
        }
        else if (v.back() == "D") {
            if (s.empty() == 1) {
                cout << "The stack is empty" << endl;
            }
            else {
                cout << "Deleted " << s.pop() << endl;
            }
        }
        else if (v.back() == "S") {
            cout << "Size of the stack: " << s.size() << endl;
        }
        else if (v.back() == "F") {
            std::cin >> value;
        }
    }
}

I was able to narrow the maximum size of the array to something between 2000000 and 3000000. If I insert value that is too big I will get a "Segmentation fault: 11" error when running compiled program. Any ideas why?

Also, I have a second question. I have a simple program that randomly generates commands for my stack. First int, that is generated by this program, determines the number of commands, so there is not need to make a bigger array than that int. I know how to pass that int to the constructor, but don't know how to create an array with that value. Thanks for help.

Aucun commentaire:

Enregistrer un commentaire