Loop Structure from Box2D Example can lead to Bugs

I just started playing around with Box2D recently, and I have to say I'm impressed. It works really well!

However, I did notice one issue when following code from the examples. The following line of code appears to be the recommended way to loop through the bodyList:

for (var bb:b2Body = m_world.m_bodyList; bb; bb = bb.m_next){
...
}

However, I found this loop can cause bugs in the following scenario:

for (var bb:b2Body = m_world.m_bodyList; bb; bb = bb.m_next){
//We process bb and realize it should be destroyed, so we call:
world.DestroyBody(bb);
}

While bb does get destroyed, this code inadvertently causes the loop to abort and anything else in the bodyList fails to get processed on that step. This is because the DestroyBody method reassigns body's "m_next" property.

Switching my loop to something like the following allowed me to preserve whatever was next in the body list regardless of what happens to the current body:

var next:b2Body = m_world.m_bodyList;
var current:b2Body;
while (next != null) {
current = next;
next = next.m_next;
//PROCESS CURRENT HERE
}

While this does seem a little convoluted, it seemed safer than attempting to alter the Box2D internals.
Good point!

Your approach is solid and applies to all languages, not just AS3.
That still bothers me a little bit - my main problem is that the way Erin wrote the loop originally is the way most people will write it, too, as it's pretty canonical. I suppose if you're destroying bodies you should probably expect something to go wrong and be more careful, but that's going to be one hell of a bug to track down if it shows up, especially for someone not familiar with the internals. The body might actually be deleted deep in another method that's called within that loop, so it won't be at all obvious that the loop structure is at fault.

The m_next pointer is currently doing double duty to link both the active body list and the deferred destruction list, which is why the loop terminates (you end up finishing up by going over just the deleted bodies). It would be possible to avoid this issue altogether internally by using a different next pointer for the destroy list, and leaving the m_next untouched after a body is tagged for deletion. I can't think of any big issues this would cause other than adding another few bytes to each body, but I might be wrong - thoughts?
Deferred destruction is gone in version 2.0.

In the debug build the Box2D allocator wipes the freed memory with FDFDFDFD, so this shouldn't be too hard to see in the debugger. The real trouble starts if you destroy then create a body with the same memory block.

I think this will be a problem for people who aren't used to dealing with linked lists. I'll make a note of this in the manual.

Original thread: https://box2d.org/forum/viewtopic.php?t=496