Segfault在我的堆栈实现(C ++)代码中,却无法理解为什么

时间:2012-07-03 07:27:56

标签: c++ stack segmentation-fault

为了直接设置记录,我对C ++很新,我在编程方面的大部分经验都是用Java编写的。我正在编写一个基于数组的堆栈实现,我似乎无法读取保存在堆栈中的任何数据。

可以推送对象,这似乎正常运行。注释掉top()操作会产生一个成功的零输出,这似乎告诉我,我知道该项目至少被添加到数组中。

然而,阅读该项目,我收到了段错误。快速谷歌或两个后,我了解到段错误意味着有一个操作访问它无权访问的数据。这让我认为我的top()函数无法访问数组。它是该类的私有成员,但我之前对OOP的了解告诉我,类方法应该可以访问所有私有变量。

有人能帮助我指出正确的方向吗? (如果文档对于这样的原始数据结构有点过分,请告诉我,是否应该删除它。)

谢谢!代码如下:

#include <iostream>
using namespace std;

/*
Class: arrayStack() 
A simple stack implemented with a single array. 
Handles char objects.
*/
class arrayStack {

    int length; //cap on stack length
    int count; //Keeps track of which element in the array to pop from.
    char array[]; //Hold data here

public: 

/*
arrayStack() 
Constructor used to create a stack object. No default constructor exists, the length (l) is a required argument as a parameter to create a stack.
l space is reserved in the array and count is set to -1, the int value required for an empty stack.
*/
arrayStack(int l) 
{
    char array[l];
    length = l;
    count = -1;
}

/*
push() -- return type void.
Method to add a desired char element (o) to the stack. 
*/
void push(char o) 
{   
    array[count] = o;
    count++; //Increment the counter to accurately pull element from array.
}

/*
pop() -- return type char.
Method to remove an element from the stack. Element is pulled from the stack and returned. 
*/
char pop() 
{
    //temp space to store pulled element before returning.
    char temp;
    temp = array[count];

    //Replace popped element with null to reduce memory waste. Then decrement counter for proper functioning of the stack.
    array[count] = '\0'; 
    count--;
    return temp;
}

/*
top() -- return type char.
Method which returns the top element of the function without deleting it from the stack. Useful for inspection and testing, but functionally very similar to pop().
*/
char top() 
{
    //temp space to store pulled element.
    char temp; 
    temp = array[count];
    return temp;
}

/*
isEmpty() -- return type boolean.
Method which checks the stack for elements. If there are no elements, the method returns true. If there exists one or more elements, the method will return false. 
Method is very simple-- a simple check against the count (int) variable. 
*/
bool isEmpty() 
{
    if (count == -1) {
        return true;
    } else {
        return false;
    }
}

/*
size() -- return type int.
Method which returns the number of elements in the stack. 
*/
int size() 
{
    return count++;
}

};

int main() {
arrayStack stack(10);
stack.push('c');
cout << stack.top(); //SEGFAULT OCCURS HERE. 
cout << stack.isEmpty();

return 0;
}

1 个答案:

答案 0 :(得分:4)

您的会员array仍然未初始化:

arrayStack(int l) 
{
    char array[l];
    length = l;
    count = -1;
}

在这里,你创建了一个新的array(我怀疑它是合法的,因为C ++不支持VLA。它应该是

arrayStack(int l) 
{
    array = new char[l];
    length = l;
    count = -1;
}

您还需要实现析构函数来删除已分配的内存。这意味着您还需要一个复制构造函数和复制赋值运算符。