2

因此,我正在开发一个程序,该程序应该“堆积”用户添加到集合中的整数等。但是,当我尝试访问作为参数传递给函数的 Node 的左子节点时,我现在遇到了问题。Visual Works 内存不足...

奇怪的是,在调试器中,我可以看到传递节点的左子节点已创建并正确分配给传递节点。但是当我尝试通过源代码访问它时,我得到了一个疯狂的内存错误。

这是相应的代码。希望它是可读的

发生错误的函数,一旦被调用:

addLeftChildTo: aNode

"Determine Left child of passed node. Set that child's parent node as self. Imprint the index where that value was retrieved from the array."

| temp leftChildIndex |
2 * aNode indexOfNode <= arrayOfInput size
    ifTrue: 
        [leftChildIndex := 2 * aNode indexOfNode.
        aNode left: (arrayOfInput at: leftChildIndex).
        aNode left parentNode: aNode.                   <---VW Runs out of memory and crashes here. This occurs once the debugger dives into the 'left' accessor method of the passed aNode object.
        aNode left indexOfNode: leftChildIndex.
        self bubbleUp: aNode left.
        self bubbleUpArrayOfInput: aNode left]
    ifFalse: [aNode left: nil]

下面是 BinaryHeapNode 类的 'left' 的访问器方法

left

    ^self left

left: aValue

    left := BinaryHeapNode new: aValue.

如果查看最初调用 addLeftChildTo: 方法的代码会有所帮助...

populateHeap
"from passed array of input"
"Add a node (typically a node with an element from the ArrayOfInput) to the heap. Bubble up as you go."

| temp |
rootNode isNil
    ifTrue: 
        [rootNode := BinaryHeapNode new: (arrayOfInput at: 1).
        rootNode indexOfNode: indexOfArray.

        self addLeftChildTo: rootNode.   <--- Call to function with problematic code. 
                    ...

我不明白我做错了什么,我已经被这个问题困住了几个小时。有任何想法吗?

4

1 回答 1

5

您使用访问器 #left 进行了无限递归:

left
  ^self left

这个方法实际上调用了它自己。而是只返回实例变量^left

于 2012-10-30T20:04:46.867 回答