# Bug in TOctree2

**URL:** <https://forums.unrealengine.com/t/bug-in-toctree2/1258070>\
**Category:** Rendering\
**Tags:** unreal-engine, crash, bug-report\
**Created:** [August 11, 2023, 6:39pm UTC](https://forums.unrealengine.com/t/bug-in-toctree2/1258070 "2023-08-11T18:39:26Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jgosztyla](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@jgosztyla](https://forums.unrealengine.com/u/jgosztyla)\
**Post date:** [August 11, 2023, 6:39pm UTC](https://forums.unrealengine.com/t/bug-in-toctree2/1258070/1 "2023-08-11T18:39:26Z")

</div>

In Math/GenericOctree.h, as part of TOctree2 there is a snippet of code in AddElementInternal that looks like this:

```auto
	TempElementStorage = MoveTemp(TreeElements[CurrentNodeIndex]);

	FNodeIndex ChildStartIndex = AllocateEightNodes();
	ParentLinks[(ChildStartIndex - 1) / 8] = CurrentNodeIndex;
	TreeNodes[CurrentNodeIndex].ChildNodes = ChildStartIndex;
	TreeNodes[CurrentNodeIndex].InclusiveNumElements = 0;

	for (typename TCallTraits<ElementType>::ConstReference ChildElement : TempElementStorage)
	{
		const FBoxCenterAndExtent ChildElementBounds(OctreeSemantics::GetBoundingBox(ChildElement));
		AddElementInternal(CurrentNodeIndex, NodeContext, ChildElementBounds, ChildElement, TempElementStorage);
	}

```

The key observation being that it is iterating over an array “TempElementStorage” that is being changed inside the recursive call of AddElementInternal. This is causing a crash.

I’m guessing most octree’s using this typically don’t run into an issue because OctreeSemantics::MaxElementsPerLeaf is set high enough to avoid this block of code.

What is the correct fix here? It seems like this code is used all over the engine, I’m surprised no one has run into this yet…

thank you,  
jeff

---

<div class="post-metadata">

**Author:** ![jgosztyla](https://d3kjluh73b9h9o.cloudfront.net/original/4X/2/8/5/28502927f1d97ba1051b3b47ccfe17233bf41ef0.png) [@jgosztyla](https://forums.unrealengine.com/u/jgosztyla)\
**Post date:** [August 11, 2023, 8:40pm UTC](https://forums.unrealengine.com/t/bug-in-toctree2/1258070/2 "2023-08-11T20:40:56Z")

</div>

Just for refrence, the semantics in the crashing case look like:

```auto
struct FBlendableOctreeSemantics
{
	enum { MaxElementsPerLeaf = 4 };
	enum { MinInclusiveElementsPerNode = 7 };
	enum { MaxNodeDepth = 32 };

	typedef TInlineAllocator<MaxElementsPerLeaf> ElementAllocator;
...

```
