Fix genHeap function to not throw StackOverflowError