2014-09-23 75 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