2014-09-23 76 views
-1

我有一个非常奇怪的错误与我的数组始终未定义的大小/ 2。我有一个链接堆栈,每个节点包含一个大小为32000的数组,问题在于每个数组的位置16000由于某种原因,该值未定义。数组大小/ 2始终未定义

节点是:

template <class myType> 
struct nodeType { 
    myType dataSet[SIZE]; 
    int top; 
    nodeType<myType> *link; 
}; 

和简单的push和pop是:

template <class myType> 
void linkedStack<myType>::push(const myType& newItem) 
{ 
    //if the count is greater than the size of one node's array, create another 
    if(count % SIZE == 0) { 
     nodeType<myType> *newNode = new nodeType<myType>; 
     newNode->top = 0; 
     newNode->link = stackTop; 
     stackTop = newNode; 
    } 
    stackTop->dataSet[stackTop->top] = newItem; 
    count++; 
    stackTop->top++; 
} 

template <class myType> 
void linkedStack<myType>::pop() 
{ 

    if(stackTop->top == 0) { 
    nodeType<myType> *toDelete = stackTop; 
    stackTop = stackTop->link; 
    delete stackTop; 
    } 
    stackTop->top--; 
    count--; 
} 

和for循环使用IM是:

for (int i=testSize2; i>0; i--) { 
    if (iStackBig.top() != i) { 
     workedStk = false; 
    } 
    iStackBig.pop(); 
} 

我做不到了解为什么地址16000未定义在节点阵列。我在做什么明显错误?

+0

它不会发生大小为31998的数组吗? – Beta 2014-09-23 23:38:23

+4

这是* begging *的[MVCE](http://stackoverflow.com/help/mcve)。 – WhozCraig 2014-09-23 23:39:51

+0

只是好奇,stackTop-> top ++和 - 正如你期望的那样工作? – 2014-09-23 23:40:42

回答

1

一个问题我看到:

if (stackTop->top == 0) { 
    nodeType<myType> *toDelete = stackTop; 
    stackTop = stackTop->link; 
    delete stackTop;   // You should be deleting toDelete here 
} 
stackTop->top--; // Oops, just used a deleted pointer 

使用之前被删除的指针调用未定义的行为,这很可能是你的问题的根源。当你从空栈中弹出时,你还应该检查stackTopstackTop->link是否为NULL。

+0

是的,那是我知道我必须做的简单的错误。谢谢! – 2014-09-24 22:17:55